ng-view

ng-view is the directive that angular uses as a container to switch between views. Let’s start by making an empty ng-view tag in our app

<body ng-app="myApp">
  <ng-view></ng-view>
</body>

ng-view will allow us to set up config function and access the $routeProvider. In the config function, the services are not yet available to us so we have to access the router through $routeProvider and not $route.

{info} ngRoute is no longer a part of the base angular.js file, so you'll need to include the angular-route.js file after your the base angular javascript file.

We can configure a route by using the “when” function of the $routeProvider. We need to first specify the route, then in a second parameter provide an object with a templateUrl property and a controller property. For now we’ll just set the templateUrl to “app.html” and the controller to “AppCtrl”. Since we're using the controllerAs syntax, we'll set the controllerAs parameter to “app”.

var app = angular.module("app", []);

app.config(function($routeProvider){
  $routeProvider.when("/",
    {
      templateUrl: "app.html",
      controller: "AppCtrl",
      controllerAs: "app"
    }
  );
});

Now we can create a controller to wire up to the route. We’ll just create a model on the scope with a message “The app routing is working!”

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!";
});

Now we need to create a template for the route. We’ll create the “app.html” file with a binding for the message within an h1 tag:

<h1>{{ app.message }}</h1>

Finally, if we load the app we should see “The app routing is working!” All that’s really going on here is we used one simple tag to load our view. This is how you create single page apps. The ng-view tag will look to the route provider in order to figure out which template needs to be rendered with which controller depending on what the current route is.