DIV CSS 佈局教程網

AngularJS學習筆記:TodoMVC範例的架構解析
編輯:關於JavaScript     

近來一直在研究 AngularJS,趁著零碎時間整理成這篇筆記。官網為 https://angularjs.org/ 。

先推薦幾份入門教材:

1. AngularJS 入門教程——較為基礎,是官方 Tutorial 的翻譯。
2. 七步從 AngularJS 菜鳥到專家——同樣基礎,會實作一個線上音樂播放網站。
3. AngularJS 開發指南——內容較全面,不過翻譯略顯晦澀。

看完這些之後,自認對 AngularJS 稍有概念,便想拿它來做點東西,於是決定分析一下用 AngularJS 寫成的 TodoMVC。TodoMVC 官網為 https://todomvc.com/ 。

專案目錄結構如下:bower_components 放了兩個資料夾,其中 angular 用來存放 angular.js,todomvc-common 則放所有 todo 專案共用的 css、js(僅用於產生左側內容,與專案本身無關)與圖片。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 服務,本質上就是回傳 get 與 put 兩個方法:get 從 localStorage 取出資料並解析為 JSON,put 則把物件轉成 JSON 字串存回 localStorage,兩者都運用了 HTML5 的 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);
            }
        });
    };
});

回傳函式中,elem 是包含該指令的元素陣列,attrs 則是該元素所有屬性組成的物件。這裡用到兩個 AngularJS 方法:$watch(watchExpression, listener, objectEquality) 註冊一個偵聽器,每當 watchExpression 變化時執行回呼;$timeout(fn[, delay][, invokeApply]) 在延時達到後執行 fn。todoFocus 指令會為元素監聽其值,一旦變為 true 便以 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 指令會在按下 Escape 鍵(keyCode 27)時,透過 scope.$apply 執行 attrs.todoEscape 指定的表達式。

接著看重點 todoCtrl.js(這支較長,直接看註解):

代碼如下:
/*global todomvc, angular */
'use strict';
todomvc.controller('TodoCtrl', function TodoCtrl($scope, $location, todoStorage, filterFilter) {
    // 從localStorage中獲取todos
    var todos = $scope.todos = todoStorage.get();

    $scope.newTodo = '';
    $scope.editedTodo = null;
    $scope.$watch('todos', function (newValue, oldValue) {
        $scope.remainingCount = filterFilter(todos, { completed: false }).length;
        $scope.completedCount = todos.length - $scope.remainingCount;
        $scope.allChecked = !$scope.remainingCount;
        if (newValue !== oldValue) {
            todoStorage.put(todos);
        }
    }, true);
    if ($location.path() === '') {
        $location.path('/');
    }
    $scope.location = $location;
    $scope.$watch('location.path()', function (path) {
        $scope.statusFilter = (path === '/active') ?
            { completed: false } : (path === '/completed') ?
            { completed: true } : null;
    });
    $scope.addTodo = function () {
        var newTodo = $scope.newTodo.trim();
        if (!newTodo.length) { return; }
        todos.push({ title: newTodo, completed: false });
        $scope.newTodo = '';
    };
    $scope.editTodo = function (todo) {
        $scope.editedTodo = todo;
        $scope.originalTodo = angular.extend({}, todo);
    };
    $scope.doneEditing = function (todo) {
        $scope.editedTodo = null;
        todo.title = todo.title.trim();
        if (!todo.title) { $scope.removeTodo(todo); }
    };
    $scope.revertEditing = function (todo) {
        todos[todos.indexOf(todo)] = $scope.originalTodo;
        $scope.doneEditing($scope.originalTodo);
    };
    $scope.removeTodo = function (todo) {
        todos.splice(todos.indexOf(todo), 1);
    };
    $scope.clearCompletedTodos = function () {
        $scope.todos = todos = todos.filter(function (val) { return !val.completed; });
    };
    $scope.markAll = function (completed) {
        todos.forEach(function (todo) { todo.completed = completed; });
    };
});

這個控制器負責:從 todoStorage 取得 todos;用 $watch 監聽 todos 變化,即時更新未完成數、已完成數與全選狀態,並在值改變時存回 localStorage;用另一個 $watch 監聽路由 path 決定篩選器 statusFilter(/active、/completed 或全部);並提供 addTodo、editTodo、doneEditing、revertEditing、removeTodo、clearCompletedTodos、markAll 等方法對應各項操作。

最後看 index.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>

接著定義 ng-cloak 樣式,含 ng-cloak 屬性者隱藏,避免顯示未經 AngularJS 處理的原始頁面:
<style>[ng-cloak] { display: none; }</style>

新增 todo 的表單綁定 model 為 newTodo,submit 觸發 todoCtrl 的 addTodo(),按 Enter 即會新增一筆:
<form id="todo-form" ng-submit="addTodo()">
    <input id="new-todo" placeholder="What needs to be done?" ng-model="newTodo" autofocus>
</form>

展示 todos 的區塊使用 ngShow 依 todos 長度決定顯示,並以 ngRepeat 搭配 filter:statusFilter 產生清單,ngClass 依 completed 與是否正在編輯切換樣式;label 雙擊進入編輯,表單中的 todoFocus 指令在編輯時自動聚焦,按 Esc 觸發 revertEditing 還原、按 Enter 或失焦觸發 doneEditing 儲存;destroy 按鈕則呼叫 removeTodo 刪除。

統計資訊區則以 ng-pluralize 依 remainingCount 顯示單複數,並依 location.path() 高亮對應的篩選連結,clear-completed 按鈕呼叫 clearCompletedTodos 清除已完成項目。

以上就是這篇筆記的整理,全為個人心得,希望對使用 AngularJS 的朋友有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved