Let’s take a closer look at the previous lesson/app, particularly the config function:
angular.module('myApp', ['ngRoute'])
.config(function($routeProvider){
$routeProvider.when("/",
{
templateUrl: "app.html",
controller: "AppCtrl",
controllerAs: "app"
}
);
})
.controller('AppCtrl', function() {
var self = this;
self.message = "The app routing is working!";
});
If we try injecting $routeProvider into our controller like so:
.controller('AppCtrl', function($routeProvider) {
We can see that we get an error in the console that $routeProviderProvider is not available. This is because it’s actually looking for a service that’s created by a provider so we only need $route. Now if we try to inject $route into our config function, we can see that we get an unknown provider error. This is because at the config phase of the app, we only have providers available to us, which are the factories that generate an instance of things like $route. So let’s try manipulating $route in our controller. Comment out what’s in our config function, and move the route declaration to our controller.
angular.module('myApp', ['ngRoute'])
/*.config(function($routeProvider){
$routeProvider.when("/",
{
templateUrl: "app.html",
controller: "AppCtrl",
controllerAs: "app"
}
);
})
*/
.controller('AppCtrl', function($route) {
$route.routes["/"] = {
templateUrl: "app.html",
controller: "AppCtrl",
controllerAs: "app"
}
var self = this;
self.message = "The app routing is working!";
});
When we load the app, we can see that we get no errors in the console, but our view is empty. This is because it is way too late in our app for us to declare this route. We need to reference “AppCtrl” so it can be initiated when we navigate to this URL. We can’t define routes in a controller or in a service since the configuration needs to happen before it gets injected into anything we want to use it in. Any configuration we do to providers in the config function will allow us to access pre-configured instances of these providers when they are injected.