AngularJS – Working with templates

2014-07-24 22:06:20

1. First you have to create new empty project

2. Next please run bower commend

if you don't know what is bower, check this out: http://bower.io/

bower install angularjs
bower install bootstrap

3. Now you can create index.html

The most important here is two directives itemAjaxTpl and itemCacheTpl. And of course script element with template 'text/ng-template' index.html

<!DOCTYPE html>

<html ng-app='"App"'>
<head lang='"en"'>
<meta charset="utf-8"/>
<title>AngularJS - Tempates</title>
<link href='"bower_components/bootstrap/dist/css/bootstrap.min.css"' rel='"stylesheet"'/>
<script src='"bower_components/angular/angular.min.js"'></script>
<script src='"app/app.js"'></script>
<script src='"app/directive.js"'></script>
<script id='"app/tpl/item-cache.tpl.html"' type='"text/ng-template"'>

    <div class=&quot;panel panel-default&quot;>
        <div class=&quot;panel-body&quot;>
            Html from index.html


4. Last html for this example is template for itemAjaxTpl directive

Template 1 - item.tpl.html

<div class='"panel' panel-default&quot;="">
<div class='"panel-body"'>
        Html from server vi ajax call.

5. Now javascript! You have to add app.js with one depedecy


var App = angular.module('App',

6. And the last file


angular.module('App.directives', [])

    .directive('itemAjaxTpl', function () {
        return {
            restrict: 'E',
            scope: {},
            templateUrl: 'app/tpl/item.tpl.html'

    .directive('itemCacheTpl', function () {
        return {
            restrict: 'E',
            scope: {},
            templateUrl: 'app/tpl/item-cache.tpl.html'


As you can see we have two directives, but only one ajax call for 'item.tpl.html' template. Template 'item-cache.tpl.html' we put in index.html.

How does AngularJS know where to look ? It know because we put template in script type="text/ng-template" id="app/tpl/item-cache.tpl.html"