AngularJS - part 4 - templates
by Krzysztof Safjanowski
HTML
<script src="https://code.angularjs.org/1.2.1/angular-route.js"></script>
<div ng-app='app'>
<p><a href="/todo">Active items</a>, <a href="/archive">Archive</a></p>
<div ng-view=""></div>
</div>
JavaScript
angular.module('app', ['ngRoute'])
.config(function($routeProvider,$locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/todo', {
template: ['<div>Total todos: {{returnTotalTodos()}}',
' <ul class="unstyled">',
' <li ng-repeat="todo in todos">',
' <input type="checkbox" ng-model="todo.done" /> <span class="done-{{todo.done}}">{{todo.todoItem}}</span>',
' </li>',
' </ul>',
' <input type="text" ng-model="newTodoText" ng-model-instant />',
' <button ng-click="addNewTodo()"><i class="icon-plus"></i>add one</button>{{newTodoText}}',
' <div>',
' <button ng-click="clearFinishedTodos()">Clear Finished Todos</button>',
' </div>',
'</div>'].join(''),
controller: 'todoController'
})
.when('/archive', {
template: '<div>archive list</div>'
}).otherwise({
redirectTo: '/todo'
});
})
.factory('items', function() {
return [{
todoItem: 'walk the dog',
done: false
}, {
todoItem: 'feed the cat',
done: false
}, {
todoItem: 'third message',
done: true
}];
})
.factory('todo', function(items) {
var todoItems = items;
function returnTotalTodos() {
console.log('returnTotalTodos executes', items);
return todoItems.length;
}
function addNewTodo(newTodoText) {
console.log('addNewTodo executes');
todoItems.push({
todoItem: newTodoText,
done: false
});
}
function clearFinishedTodos() {
console.log('clearFinishedTodos executes');
return todoItems = todoItems.filter(function (todo) {
return !todo.done
});
}
return {
returnTotalTodos: returnTotalTodos,
addNewTodo: addNewTodo,
clearFinishedTodos: clearFinishedTodos
}
})
.controller('todoController', function($scope, items, todo) {
$scope.todos = items;
...