My Technical Notes

Thursday, 13 August 2015

Angular: Embedding Template in Page

Most Angular examples that explain how to use `$routeProvider`, will show you how to load a specific controller and view in response to a specific route will tell you to specify the `templateUrl` property as a url to the template file. For example:


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

app.config(function($routeProvider) {
    $routeProvider
        .when('/customers', { templateUrl: '/app/views/customers/customersList.html', controller : 'CustomerController' })
        .otherwise({ redirectTo: '/customers' });
});

The above example makes use of a template file located at `/app/.../customersList.html`. What if we wanted to embed the content of `customersList.html` into the main page? To do this, we use a script tag with the type set to `text/ng-template`:


<script type='text/ng-template' id='customerListTemplate.html'>

This is the customer list template

</script>

Thereafter we provide the `id` property as the `templateUrl`:


app.config(function($routeProvider) {
    $routeProvider
        .when('/customers', { templateUrl: 'customersListTemplate.html', controller : 'CustomerController' })
        .otherwise({ redirectTo: '/customers' });
});

Just a view remarks - the embedded template must be inside the tag with `ng-app` directive.

No comments: