AngularJS学习笔记之TodoMVC的剖判

作者: 计算机网络  发布:2019-09-06

近期一段时间一向在看AngularJS,趁着一点光阴计算一下。

AngularJS学习笔记之TodoMVC的剖析,angularjstodomvc

不久前一段时间一向在看AngularJS,趁着一点时日计算一下。

官方网址地址:

先引入多少个科目

  1. AngularJS入门教程 相比较基础,是官方Tutorial的翻译。

  2. 七步从AngularJS新手到学者 也比较基础,制作了二个在线音乐播放网址。

  3. AngularJS开采指南 那么些科目相比较完善,但自个儿备感翻译的多少拗口难懂。

看过这几个课程后,觉得AngularJS也懂一点了,就想用它干点事,就深入分析一下AngularJS写的todomvc吧。

Todomvc官方网址地址:

类型的目录如下:

bower_components里放了四个公文夹,当中angular文件夹是用来一如angular.js文件的,todomvc-common文件夹里的放入了具有todo项目联合的cssjs(只是用来生成左侧内容的,与系列无关)和图表。

js文件夹是金锭,里面放了相应的controller(控制器)directive(指令)service(服务)和app.js。

test文件夹里放的是测量检验用的代码,不剖判。

index.html是体系的view页面。

先来看一下app.js

复制代码 代码如下:

/*global angular */
/*jshint unused:false */
'use strict';
/**
 * The main TodoMVC app module
 *
 * @type {angular.Module}
 */
var todomvc = angular.module('todomvc', []);

正是概念了一个模块todomvc

再看一下services下的todoStorage.js

复制代码 代码如下:

/*global todomvc */
'use strict';
/**
 * Services that persists and retrieves TODOs from localStorage
 */
todomvc.factory('todoStorage', function () {
    // todos JSON字符串存款和储蓄的独一无二标记
    var STORAGE_ID = 'todos-angularjs';
    return {
        // 从localStorage中抽出todos,并解析成JSON对象
        get: function () {
            return JSON.parse(localStorage.getItem(STORAGE_ID) || '[]');
        },
        // 将todos对象转化成JSON字符串,并存入localStorage
        put: function (todos) {
            localStorage.setItem(STORAGE_ID, JSON.stringify(todos));
        }
    };
});

选取factory方法成立了todoStorage的service方法,那一个service方法的真面目便是回来了八个主意get和put,两个都以用了JSON2和HTML5的天性。get将todos的内容从localStorage中抽出,并剖析成JSON,put将todos转化成JSON字符串,并累积到localStorage中。

再看一下directives下边包车型大巴三个指令文件。

todoFocus.js

复制代码 代码如下:

/*global todomvc */
'use strict';
/**
 * Directive that places focus on the element it is applied to when the expression it binds to evaluates to true
 */
todomvc.directive('todoFocus', function todoFocus($timeout) {
    return function (scope, elem, attrs) {
        // 为todoFocus属性的值增加监听
        scope.$watch(attrs.todoFocus, function (newVal) {
            if (newVal) {
                $timeout(function () {
                    elem[0].focus();
                }, 0, false);
            }
        });
    };
});

归来function的参数中,elem就是包罗该指令的要素的数组,attrs是因素的富有属性、属性名等组成的对象。

个中使用了三个AngularJS的艺术

$watch(watchExpression, listener, objectEquality) 注册一个侦听器回调,每当watchExpression变化时,监听回调将被推行。

$timeout(fn[, delay][, invokeApply]) 当timeout的值高达时,实施fn函数。

todoFocus.js成立了todoFocus指令。当贰个要素具备todoFocus属性时,该指令会为该因素的todoFocus属性的值增添监听,若是todoFocus属性的值改形成true,就能推行$timeout(function () {elem[0].focus();}, 0, false);个中的延迟时间为0秒,所以会应声实践elem[0].focus()。

todoEscape.js

复制代码 代码如下:

/*global todomvc */
'use strict';
/**
 * Directive that executes an expression when the element it is applied to gets
 * an `escape` keydown event.
 */
todomvc.directive('todoEscape', function () {
    var ESCAPE_KEY = 27;
    return function (scope, elem, attrs) {
        elem.bind('keydown', function (event) {
            if (event.keyCode === ESCAPE_KEY) {
                scope.$apply(attrs.todoEscape);
            }
        });
    };
});

todoEscape.js创制了todoEscape指令。当按下Escape键时,试行attrs.todoEscape的表达式。

看一下金元,controllers文件夹中的todoCtrl.js,那些文件略长,笔者就一向写注释了。

复制代码 代码如下:

/*global todomvc, angular */
'use strict';
/**
 * The main controller for the app. The controller:
 * - retrieves and persists the model via the todoStorage service
 * - exposes the model to the template and provides event handlers
 */
todomvc.controller('TodoCtrl', function TodoCtrl($scope, $location, todoStorage, filterFilter) {
    // 从localStorage中获取todos
    var todos = $scope.todos = todoStorage.get();

    // 记录新的todo
    $scope.newTodo = '';
    // 记录编辑过的todo
    $scope.editedTodo = null;
    // 当todos的值改动时实行个中的法子
    $scope.$watch('todos', function (newValue, oldValue) {
        // 获取未产生的todos的多少
        $scope.remainingCount = filterFilter(todos, { completed: false }).length;
        // 获取已产生的todos的数据
        $scope.completedCount = todos.length - $scope.remainingCount;
        // 当且仅当$scope.remainingCount为0时,$scope.allChecked为true
        $scope.allChecked = !$scope.remainingCount;
        // 当todos的新值和旧值不对等时,向localStorage中存入todos
        if (newValue !== oldValue) { // This prevents unneeded calls to the local storage
            todoStorage.put(todos);
        }
    }, true);
    if ($location.path() === '') {
        // 若是$location.path()为空,就安装为/
        $location.path('/');
    }
    $scope.location = $location;
    // 当location.path()的值改换时施行个中的艺术
    $scope.$watch('location.path()', function (path) {
        // 获取状态的过滤器
        // 倘若path为'/active',过滤器为{ completed: false }
        // 倘诺path为'/completed',过滤器为{ completed: true }
        // 不然,过滤器为null
        $scope.statusFilter = (path === '/active') ?
            { completed: false } : (path === '/completed') ?
            { completed: true } : null;
    });
    // 加多贰个新的todo
    $scope.addTodo = function () {
        var newTodo = $scope.newTodo.trim();
        if (!newTodo.length) {
            return;
        }
        // 向todos里增多一个todo,completed属性默以为false
        todos.push({
            title: newTodo,
            completed: false
        });
        // 置空
        $scope.newTodo = '';
    };
    // 编辑三个todo
    $scope.editTodo = function (todo) {
        $scope.editedTodo = todo;
        // Clone the original todo to restore it on demand.
        // 保存编辑前的todo,为复原编辑前做计划
        $scope.originalTodo = angular.extend({}, todo);
    };
    // 编辑todo完成
    $scope.doneEditing = function (todo) {
        // 置空
        $scope.editedTodo = null;
        todo.title = todo.title.trim();
        if (!todo.title) {
            // 假设todo的title为空,则移除该todo
            $scope.removeTodo(todo);
        }
    };
    // 苏醒编辑前的todo
    $scope.revertEditing = function (todo) {
        todos[todos.indexOf(todo)] = $scope.originalTodo;
        $scope.doneEditing($scope.originalTodo);
    };
    // 移除todo
    $scope.removeTodo = function (todo) {
        todos.splice(todos.indexOf(todo), 1);
    };
    // 清除已产生的todos
    $scope.clearCompletedTodos = function () {
        $scope.todos = todos = todos.filter(function (val) {
            return !val.completed;
        });
    };
    // 标志全部的todo的意况(true或false)
    $scope.markAll = function (completed) {
        todos.forEach(function (todo) {
            todo.completed = completed;
        });
    };
});

 最终看一下index.html,那几个文件大家一段一段的剖释。

复制代码 代码如下:

<!doctype html>
<html lang="en" ng-app="todomvc" data-framework="angularjs">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>AngularJS • TodoMVC</title>
        <link rel="stylesheet" href="bower_components/todomvc-common/base.css">
        <style>[ng-cloak] { display: none; }</style>
    </head>
    <body>
        <section id="todoapp" ng-controller="TodoCtrl">
            <header id="header">
                <h1>todos</h1>
                <form id="todo-form" ng-submit="addTodo()">
                    <input id="new-todo" placeholder="What needs to be done?" ng-model="newTodo" autofocus>
                </form>
            </header>
            <section id="main" ng-show="todos.length" ng-cloak>
                <input id="toggle-all" type="checkbox" ng-model="allChecked" ng-click="markAll(allChecked)">
                <label for="toggle-all">Mark all as complete</label>
                <ul id="todo-list">
                    <li ng-repeat="todo in todos | filter:statusFilter track by $index" ng-class="{completed: todo.completed, editing: todo == editedTodo}">
                        <div class="view">
                            <input class="toggle" type="checkbox" ng-model="todo.completed">
                            <label ng-dblclick="editTodo(todo)">{{todo.title}}</label>
                            <button class="destroy" ng-click="removeTodo(todo)"></button>
                        </div>
                        <form ng-submit="doneEditing(todo)">
                            <input class="edit" ng-trim="false" ng-model="todo.title" todo-escape="revertEditing(todo)" ng-blur="doneEditing(todo)" todo-focus="todo == editedTodo">
                        </form>
                    </li>
                </ul>
            </section>
            <footer id="footer" ng-show="todos.length" ng-cloak>
                <span id="todo-count"><strong>{{remainingCount}}</strong>
                    <ng-pluralize count="remainingCount" when="{ one: 'item left', other: 'items left' }"></ng-pluralize>
                </span>
                <ul id="filters">
                    <li>
                        <a ng-class="{selected: location.path() == '/'} " href="#/">All</a>
                    </li>
                    <li>
                        <a ng-class="{selected: location.path() == '/active'}" href="#/active">Active</a>
                    </li>
                    <li>
                        <a ng-class="{selected: location.path() == '/completed'}" href="#/completed">Completed</a>
                    </li>
                </ul>
                <button id="clear-completed" ng-click="clearCompletedTodos()" ng-show="completedCount">Clear completed ({{completedCount}})</button>
            </footer>
        </section>
        <footer id="info">
            <p>Double-click to edit a todo</p>
            <p>Credits:
                <a href=" Burgdorf</a>,
                <a href=" Bidelman</a>,
                <a href=" Mumm</a> and
                <a href=" Minar</a>
            </p>
            <p>Part of <a href=";
        </footer>
        <script src="bower_components/todomvc-common/base.js"></script>
        <script src="bower_components/angular/angular.js"></script>
        <script src="js/app.js"></script>
        <script src="js/controllers/todoCtrl.js"></script>
        <script src="js/services/todoStorage.js"></script>
        <script src="js/directives/todoFocus.js"></script>
        <script src="js/directives/todoEscape.js"></script>
    </body>
</html>

率先是在最上面,引进相应的JS,那么些就相当的少说了。

复制代码 代码如下:

<script src="bower_components/todomvc-common/base.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/todoCtrl.js"></script>
<script src="js/services/todoStorage.js"></script>
<script src="js/directives/todoFocus.js"></script>
<script src="js/directives/todoEscape.js"></script>

定义style[ng-cloak],含有ng-cloak属性则不可知。

复制代码 代码如下:

<style>[ng-cloak] { display: none; }</style>

来看加多todo的html,绑定的model为newTodo,submit的点子是todoCtrl.js中的addTodo(),会加多一条todo,点击Enter,暗许触发提交事件,就接触了addTodo()方法,增加了一条todo到todos中。

复制代码 代码如下:

<form id="todo-form" ng-submit="addTodo()">
    <input id="new-todo" placeholder="What needs to be done?" ng-model="newTodo" autofocus>
</form>

再看显示todos的html

复制代码 代码如下:

<section id="main" ng-show="todos.length" ng-cloak>
    <input id="toggle-all" type="checkbox" ng-model="allChecked" ng-click="markAll(allChecked)">
    <label for="toggle-all">Mark all as complete</label>
    <ul id="todo-list">
        <li ng-repeat="todo in todos | filter:statusFilter track by $index" ng-class="{completed: todo.completed, editing: todo == editedTodo}">
            <div class="view">
                <input class="toggle" type="checkbox" ng-model="todo.completed">
                <label ng-dblclick="editTodo(todo)">{{todo.title}}</label>
                <button class="destroy" ng-click="removeTodo(todo)"></button>
            </div>
            <form ng-submit="doneEditing(todo)">
                <input class="edit" ng-trim="false" ng-model="todo.title" todo-escape="revertEditing(todo)" ng-blur="doneEditing(todo)" todo-focus="todo == editedTodo">
            </form>
        </li>
    </ul>
</section>

section使用ngShow方法依照todos的长短判定是不是出示,加上ng-cloak属性是为着在刚开端时毫不展现出AngularJS未处理的页面。能够去掉刷新试一试。

里头id为toggle-all的checkbox绑定到allChecked model上,点击触发markAll(allChecked),将allChecked的值传入,标识全体的todos。

使用ngRepeat循环发生li标签,todo in todos | filter:statusFilter track by $index,循环todos,用statusFilter过滤,用$index追踪。ngClass绑定了八个class,{completed: todo.completed, editing: todo == editedTodo},尽管todo.completed为true,增多completed class,假如todo==editedTodo,则加多editing class。class为toggle的checkbox绑定到todo.completed。todo标题显示的label绑定了双击事件,双击触发editTodo(todo),editTodo会将todo赋给editedTodo,然后会接触上边form中的todoFocus指令,这时候form中的input可知。按Esc就触发revert艾德iting(todo),苏醒到编辑前,按Enter可能失去大旨就触发doneEditing(todo) ,保存编辑后的todo。class为destroy的button绑定了click事件,点击触发removeTodo(todo),删除掉该条todo。

谈到底看todos的总计音信显示的html

复制代码 代码如下:

<footer id="footer" ng-show="todos.length" ng-cloak>
    <span id="todo-count"><strong>{{remainingCount}}</strong>
        <ng-pluralize count="remainingCount" when="{ one: 'item left', other: 'items left' }"></ng-pluralize>
    </span>
    <ul id="filters">
        <li>
            <a ng-class="{selected: location.path() == '/'} " href="#/">All</a>
        </li>
        <li>
            <a ng-class="{selected: location.path() == '/active'}" href="#/active">Active</a>
        </li>
        <li>
            <a ng-class="{selected: location.path() == '/completed'}" href="#/completed">Completed</a>
        </li>
    </ul>
    <button id="clear-completed" ng-click="clearCompletedTodos()" ng-show="completedCount">Clear completed ({{completedCount}})</button>
</footer>

ng-pluralize标签完成了当remainingCount个数为1时,突显 item left,不然展现 items left。

id为filters的ul标签中根据location.path()的源委区别,标识差异的a标签被选中。

id为clear-completed的button增加了点击事件,触发clearCompletedTodos(),清除掉全体已产生的todo。

今日的笔记就先到那边吧,都以些个人体会,希望小友人们能够欣赏。

近日一段时间一贯在看AngularJS,趁着一点光阴计算一下。 官方网址地址: 先推荐...

官方网站地址:

先引进多少个科目

  1. AngularJS入门教程 相比较基础,是官方Tutorial的翻译。

  2. 七步从AngularJS新手到学者 也正如基础,制作了二个在线音乐播放网址。

  3. AngularJS开垦指南 那么些课程相比完美,但自小编认为到翻译的略微别扭难懂。

看过这几个科目后,感觉AngularJS也懂一点了,就想用它干点事,就剖判一下AngularJS写的todomvc吧。

Todomvc官方网址地址:

品类的目录如下:

bower_components里放了五个文本夹,在那之中angular文件夹是用来一如angular.js文本的,todomvc-common文件夹里的归入了具有todo项目统一的cssjs(只是用来生成右边内容的,与类型无关)和图表。

js文件夹是大头,里面放了相应的controller(调控器)directive(指令)service(服务)和app.js。

test文件夹里放的是测量试验用的代码,不分析。

index.html是项目标view页面。

先来看一下app.js

复制代码 代码如下:

/*global angular */
/*jshint unused:false */
'use strict';
/**
 * The main TodoMVC app module
 *
 * @type {angular.Module}
 */
var todomvc = angular.module('todomvc', []);

正是概念了多少个模块todomvc

再看一下services下的todoStorage.js

复制代码 代码如下:

/*global todomvc */
'use strict';
/**
 * Services that persists and retrieves TODOs from localStorage
 */
todomvc.factory('todoStorage', function () {
    // todos JSON字符串存款和储蓄的不今不古标志
    var STORAGE_ID = 'todos-angularjs';
    return {
        // 从localStorage中抽出todos,并深入分析成JSON对象
        get: function () {
            return JSON.parse(localStorage.getItem(STORAGE_ID) || '[]');
        },
        // 将todos对象转化成JSON字符串,并存入localStorage
        put: function (todos) {
            localStorage.setItem(STORAGE_ID, JSON.stringify(todos));
        }
    };
});

利用factory方法创造了todoStorage的service方法,这几个service方法的原形便是回到了多个法子get和put,两个都是用了JSON2和HTML5的特点。get将todos的内容从localStorage中抽出,并剖判成JSON,put将todos转化成JSON字符串,并积存到localStorage中。

再看一下directives上面包车型客车八个指令文件。

todoFocus.js

复制代码 代码如下:

/*global todomvc */
'use strict';
/**
 * Directive that places focus on the element it is applied to when the expression it binds to evaluates to true
 */
todomvc.directive('todoFocus', function todoFocus($timeout) {
    return function (scope, elem, attrs) {
        // 为todoFocus属性的值增加监听
        scope.$watch(attrs.todoFocus, function (newVal) {
            if (newVal) {
                $timeout(function () {
                    elem[0].focus();
                }, 0, false);
            }
        });
    };
});

回到function的参数中,elem正是含有该指令的要素的数组,attrs是因素的兼具属性、属性名等组合的对象。

内部使用了三个AngularJS的点子

$watch(watchExpression, listener, objectEquality) 注册三个侦听器回调,每当watchExpression变化时,监听回调将被实施。

$timeout(fn[, delay][, invokeApply]) 当timeout的值高达时,实践fn函数。

todoFocus.js创立了todoFocus指令。当四个要素具备todoFocus属性时,该指令会为该因素的todoFocus属性的值加多监听,假诺todoFocus属性的值改换成true,就能够推行$timeout(function () {elem[0].focus();}, 0, false);个中的延迟时间为0秒,所以会立即推行elem[0].focus()。

todoEscape.js

复制代码 代码如下:

/*global todomvc */
'use strict';
/**
 * Directive that executes an expression when the element it is applied to gets
 * an `escape` keydown event.
 */
todomvc.directive('todoEscape', function () {
    var ESCAPE_KEY = 27;
    return function (scope, elem, attrs) {
        elem.bind('keydown', function (event) {
            if (event.keyCode === ESCAPE_KEY) {
                scope.$apply(attrs.todoEscape);
            }
        });
    };
});

todoEscape.js成立了todoEscape指令。当按下Escape键时,实践attrs.todoEscape的表明式。

看一下银元,controllers文件夹中的todoCtrl.js,那么些文件略长,笔者就直接写注释了。

复制代码 代码如下:

/*global todomvc, angular */
'use strict';
/**
 * The main controller for the app. The controller:
 * - retrieves and persists the model via the todoStorage service
 * - exposes the model to the template and provides event handlers
 */
todomvc.controller('TodoCtrl', function TodoCtrl($scope, $location, todoStorage, filterFilter) {
    // 从localStorage中获取todos
    var todos = $scope.todos = todoStorage.get();

    // 记录新的todo
    $scope.newTodo = '';
    // 记录编辑过的todo
    $scope.editedTodo = null;
    // 当todos的值退换时施行其中的章程
    $scope.$watch('todos', function (newValue, oldValue) {
        // 获取未形成的todos的数额
        $scope.remainingCount = filterFilter(todos, { completed: false }).length;
        // 获取已成功的todos的多寡
        $scope.completedCount = todos.length - $scope.remainingCount;
        // 当且仅当$scope.remainingCount为0时,$scope.allChecked为true
        $scope.allChecked = !$scope.remainingCount;
        // 当todos的新值和旧值不对等时,向localStorage中存入todos
        if (newValue !== oldValue) { // This prevents unneeded calls to the local storage
            todoStorage.put(todos);
        }
    }, true);
    if ($location.path() === '') {
        // 若是$location.path()为空,就安装为/
        $location.path('/');
    }
    $scope.location = $location;
    // 当location.path()的值改换时施行当中的办法
    $scope.$watch('location.path()', function (path) {
        // 获取状态的过滤器
        // 假若path为'/active',过滤器为{ completed: false }
        // 假诺path为'/completed',过滤器为{ completed: true }
        // 不然,过滤器为null
        $scope.statusFilter = (path === '/active') ?
            { completed: false } : (path === '/completed') ?
            { completed: true } : null;
    });
    // 增多一个新的todo
    $scope.addTodo = function () {
        var newTodo = $scope.newTodo.trim();
        if (!newTodo.length) {
            return;
        }
        // 向todos里加多四个todo,completed属性默以为false
        todos.push({
            title: newTodo,
            completed: false
        });
        // 置空
        $scope.newTodo = '';
    };
    // 编辑三个todo
    $scope.editTodo = function (todo) {
        $scope.editedTodo = todo;
        // Clone the original todo to restore it on demand.
        // 保存编辑前的todo,为复苏编辑前做计划
        $scope.originalTodo = angular.extend({}, todo);
    };
    // 编辑todo完成
    $scope.doneEditing = function (todo) {
        // 置空
        $scope.editedTodo = null;
        todo.title = todo.title.trim();
        if (!todo.title) {
            // 固然todo的title为空,则移除该todo
            $scope.removeTodo(todo);
        }
    };
    // 恢复生机编辑前的todo
    $scope.revertEditing = function (todo) {
        todos[todos.indexOf(todo)] = $scope.originalTodo;
        $scope.doneEditing($scope.originalTodo);
    };
    // 移除todo
    $scope.removeTodo = function (todo) {
        todos.splice(todos.indexOf(todo), 1);
    };
    // 清除已形成的todos
    $scope.clearCompletedTodos = function () {
        $scope.todos = todos = todos.filter(function (val) {
            return !val.completed;
        });
    };
    // 标识全体的todo的处境(true或false)
    $scope.markAll = function (completed) {
        todos.forEach(function (todo) {
            todo.completed = completed;
        });
    };
});

 最终看一下index.html,那一个文件大家一段一段的分析。

复制代码 代码如下:

<!doctype html>
<html lang="en" ng-app="todomvc" data-framework="angularjs">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>AngularJS • TodoMVC</title>
        <link rel="stylesheet" href="bower_components/todomvc-common/base.css">
        <style>[ng-cloak] { display: none; }</style>
    </head>
    <body>
        <section id="todoapp" ng-controller="TodoCtrl">
            <header id="header">
                <h1>todos</h1>
                <form id="todo-form" ng-submit="addTodo()">
                    <input id="new-todo" placeholder="What needs to be done?" ng-model="newTodo" autofocus>
                </form>
            </header>
            <section id="main" ng-show="todos.length" ng-cloak>
                <input id="toggle-all" type="checkbox" ng-model="allChecked" ng-click="markAll(allChecked)">
                <label for="toggle-all">Mark all as complete</label>
                <ul id="todo-list">
                    <li ng-repeat="todo in todos | filter:statusFilter track by $index" ng-class="{completed: todo.completed, editing: todo == editedTodo}">
                        <div class="view">
                            <input class="toggle" type="checkbox" ng-model="todo.completed">
                            <label ng-dblclick="editTodo(todo)">{{todo.title}}</label>
                            <button class="destroy" ng-click="removeTodo(todo)"></button>
                        </div>
                        <form ng-submit="doneEditing(todo)">
                            <input class="edit" ng-trim="false" ng-model="todo.title" todo-escape="revertEditing(todo)" ng-blur="doneEditing(todo)" todo-focus="todo == editedTodo">
                        </form>
                    </li>
                </ul>
            </section>
            <footer id="footer" ng-show="todos.length" ng-cloak>
                <span id="todo-count"><strong>{{remainingCount}}</strong>
                    <ng-pluralize count="remainingCount" when="{ one: 'item left', other: 'items left' }"></ng-pluralize>
                </span>
                <ul id="filters">
                    <li>
                        <a ng-class="{selected: location.path() == '/'} " href="#/">All</a>
                    </li>
                    <li>
                        <a ng-class="{selected: location.path() == '/active'}" href="#/active">Active</a>
                    </li>
                    <li>
                        <a ng-class="{selected: location.path() == '/completed'}" href="#/completed">Completed</a>
                    </li>
                </ul>
                <button id="clear-completed" ng-click="clearCompletedTodos()" ng-show="completedCount">Clear completed ({{completedCount}})</button>
            </footer>
        </section>
        <footer id="info">
            <p>Double-click to edit a todo</p>
            <p>Credits:
                <a href=" Burgdorf</a>,
                <a href=" Bidelman</a>,
                <a href=" Mumm</a> and
                <a href=" Minar</a>
            </p>
            <p>Part of <a href=">
        </footer>
        <script src="bower_components/todomvc-common/base.js"></script>
        <script src="bower_components/angular/angular.js"></script>
        <script src="js/app.js"></script>
        <script src="js/controllers/todoCtrl.js"></script>
        <script src="js/services/todoStorage.js"></script>
        <script src="js/directives/todoFocus.js"></script>
        <script src="js/directives/todoEscape.js"></script>
    </body>
</html>

率先是在最下边,引进相应的JS,那几个就非常的少说了。

复制代码 代码如下:

<script src="bower_components/todomvc-common/base.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/todoCtrl.js"></script>
<script src="js/services/todoStorage.js"></script>
<script src="js/directives/todoFocus.js"></script>
<script src="js/directives/todoEscape.js"></script>

定义style[ng-cloak],含有ng-cloak属性则不可知。

复制代码 代码如下:

<style>[ng-cloak] { display: none; }</style>

来看加多todo的html,绑定的model为newTodo,submit的不二等秘书籍是todoCtrl.js中的addTodo(),会增多一条todo,点击Enter,暗许触发提交事件,就接触了addTodo()方法,加多了一条todo到todos中。

复制代码 代码如下:

<form id="todo-form" ng-submit="addTodo()">
    <input id="new-todo" placeholder="What needs to be done?" ng-model="newTodo" autofocus>
</form>

再看展现todos的html

复制代码 代码如下:

<section id="main" ng-show="todos.length" ng-cloak>
    <input id="toggle-all" type="checkbox" ng-model="allChecked" ng-click="markAll(allChecked)">
    <label for="toggle-all">Mark all as complete</label>
    <ul id="todo-list">
        <li ng-repeat="todo in todos | filter:statusFilter track by $index" ng-class="{completed: todo.completed, editing: todo == editedTodo}">
            <div class="view">
                <input class="toggle" type="checkbox" ng-model="todo.completed">
                <label ng-dblclick="editTodo(todo)">{{todo.title}}</label>
                <button class="destroy" ng-click="removeTodo(todo)"></button>
            </div>
            <form ng-submit="doneEditing(todo)">
                <input class="edit" ng-trim="false" ng-model="todo.title" todo-escape="revertEditing(todo)" ng-blur="doneEditing(todo)" todo-focus="todo == editedTodo">
            </form>
        </li>
    </ul>
</section>

section使用ngShow方法依据todos的尺寸剖断是还是不是出示,加上ng-cloak属性是为着在刚伊始时毫无突显出AngularJS未管理的页面。能够去掉刷新试一试。

里头id为toggle-all的checkbox绑定到allChecked model上,点击触发markAll(allChecked),将allChecked的值传入,标志全部的todos。

选拔ngRepeat循环发生li标签,todo in todos | filter:statusFilter track by $index,循环todos,用statusFilter过滤,用$index追踪。ngClass绑定了七个class,{completed: todo.completed, editing: todo == editedTodo},假诺todo.completed为true,加多completed class,借使todo==editedTodo,则增加editing class。class为toggle的checkbox绑定到todo.completed。todo标题展现的label绑定了双击事件,双击触发editTodo(todo),editTodo会将todo赋给editedTodo,然后会触发上面form中的todoFocus指令,那时候form中的input可见。按Esc就触发revert艾德iting(todo),复苏到编辑前,按Enter或许失去核心就触发doneEditing(todo) ,保存编辑后的todo。class为destroy的button绑定了click事件,点击触发removeTodo(todo),删除掉该条todo。

末段看todos的计算音信呈现的html

复制代码 代码如下:

<footer id="footer" ng-show="todos.length" ng-cloak>
    <span id="todo-count"><strong>{{remainingCount}}</strong>
        <ng-pluralize count="remainingCount" when="{ one: 'item left', other: 'items left' }"></ng-pluralize>
    </span>
    <ul id="filters">
        <li>
            <a ng-class="{selected: location.path() == '/'} " href="#/">All</a>
        </li>
        <li>
            <a ng-class="{selected: location.path() == '/active'}" href="#/active">Active</a>
        </li>
        <li>
            <a ng-class="{selected: location.path() == '/completed'}" href="#/completed">Completed</a>
        </li>
    </ul>
    <button id="clear-completed" ng-click="clearCompletedTodos()" ng-show="completedCount">Clear completed ({{completedCount}})</button>
</footer>

ng-pluralize标签完毕了当remainingCount个数为1时,展现 item left,不然显示 items left。

id为filters的ul标签中依照location.path()的开始和结果不一,标识分歧的a标签被入选。

id为clear-completed的button增添了点击事件,触发clearCompletedTodos(),清除掉全体已变成的todo。

前几日的笔记就先到此地呢,都是些个人感受,希望小同伙们能够欣赏。

你大概感兴趣的文章:

  • AngularJS中的DOM操功能法分析
  • AngularJS HTML DOM详解及示范代码
  • AngularJS 入门教程之HTML DOM实例详解
  • indexedDB bootstrap angularjs之 MVC DOMO (应用示范)
  • 简要介绍AngularJS的HTML DOM协助景况
  • AngularJS中watch监听用法分析
  • AngularJS模板加载用法详解
  • AngularJS完结动态编写翻译增多到dom中的方法

本文由今晚开什么码发布于计算机网络,转载请注明出处:AngularJS学习笔记之TodoMVC的剖判

关键词: