AngularJS - part 2 - factory

by Krzysztof Safjanowski

HTML

<div ng-app='app'>
    <div ng-controller="todoController">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>
</div>

JavaScript

angular.module('app', [])
.factory('items', function() {
    return [{
        todoItem: 'walk the dog',
        done: false
    }, {
        todoItem: 'feed the cat',
        done: false
    }, {
        todoItem: 'third message',
        done: true
    }];
})
.controller('todoController', function($scope, items) {

    $scope.todos = items;

    $scope.returnTotalTodos = function () {
        console.log('returnTotalTodos executes');
        return $scope.todos.length;
    }

    $scope.addNewTodo = function () {
        console.log('addNewTodo executes');
        var nothing = $scope.todos.length;
        if ($scope.newTodoText.length) {
            $scope.todos.push({
                todoItem: $scope.newTodoText,
                done: false
            });
            $scope.newTodoText = '';
        }
    }

    $scope.clearFinishedTodos = function () {
        console.log('clearFinishedTodos executes');
        $scope.todos = $scope.todos.filter(function (todo) {
            return !todo.done
        })
    }
});