NG-View routing and templates, simple example

The ng-view directive tells angular wich DOM element to use as the element for loading and switching templates. You index.html will look like this:

<html ng-app="prutsApp">
<head>
    <title>Angular pruts</title>
</head>
<body ng-controller="pruts">
    <nav>
        <a href="#prutserd">Prutserd</a>
        <a href="#prutsers">Prutsers</a>
    </nav>
    <div ng-view>
        <p>Dit is de titel:{{title}}</p>   
    </div>
</body>
</html>

So we have an angular app called prutsApp and we have a controller called pruts. There is a navigation section wich navigate to pruterd and prutsers.

We want angular to catch the routing and loads the templates for the url's in the ng-view element, what we have to do for that is to create the configuration section for angular and declare the routes. Like this:

var prutsApp = angular.module('prutsApp', ['ngRoute']);

prutsApp.config(['$routeProvider', function ($routeProvider) {
    $routeProvider .when('/prutserd', {
        templateUrl: '/templates/prutserd.html',
        controller: 'prutserd'
    }).
    when('/prutsers', {
        templateUrl: '/templates/prutsers.html',
        controller: 'prutsers'
    })
}]);

You can see the dependency injection working. In the app we inject ngRoute in the app and can use $routeProvider in the config. In general you can place your templates in a template folder or spits things up in seperate folders. If you are using a MVC project remember that you cannot place your template folder into the views folder ( what would be the most logical place ). The view folder is for security reasons protecten and can only be reached through controller actions but if you place your template directory in the root of your project everything is working fine.

We have created routes for prutserd and prutsers and as you can see we assigned a controller to that specific template. To maken that work the controller have to exist, like this:

prutsApp.controller('pruts', ['$scope', function ($scope) {
    $scope.title = "pruts";
}]);

prutsApp.controller('prutserd', ['$scope', function ($scope) {
    $scope.title = "prutserd";
}]);

prutsApp.controller('prutsers', ['$scope', function ($scope) {
    $scope.title = "prutsers";
}]);

Now we can build a template wich use the controller and property's on it, something like this:

<div ng-controller=\"prutserd\">
    <p>{{title}}</p>
</div>

And that's all you have to do to use the routing engine of angular.

{{opmerking.Naam}}:

{{opmerking.OpmerkingText}}

            

Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!