Angular.js學習之路一:使用angular.js實現todomvc

須要的知識

html、js、初步瞭解angularjs
熟悉npm、git的操做

起步

  • 在github上給咱們提供了一個todomvc的模板,咱們能夠clone下來,使用html

  • 安裝npm,安裝git(具體安裝不在描述,請自行百度)node

  • 在本地新建文件夾todomvc,打開終端進入當前目錄,執行下面的命令git

    git clone https://github.com/tastejs/todomvc-app-template.git
      cd todomvc-app-template/
      npm install
      npm uninstall todomvc-common --save
      npm install angular --save
  • 到此項目模板以構建完成angularjs

實現

  • 使用開發工具打開目錄github

  • 打開index.html,在<body>的最下面添加angular.js的引用npm

    <script src="node_modules/angular/angular.js"></script>
  • 打開app.js將window對象換成angular對象,代碼結構以下:mvc

    (function (angular) {
        'use strict';
    })(angular);
  • 建立一個模塊:app

    var myApp = angular.module('MyTodoMvc', []);
  • 建立一個Controllerdom

    myApp.controller('MainController', ['$scope', function ($scope) {
     };
  • 暴露text到頁面ide

    $scope.text = "";
  • 暴露todos到頁面

    $scope.todos = [
           {
               id: 1,
               text: '學習',
               completed: false
           },
           {
               id: 2,
               text: '睡覺',
               completed: false
           },
           {
               id: 3,
               text: '敲代碼',
               completed: true
           }
       ];
  • 在index.html中找到顯示數據的ul,留下一個ul,刪除其他的ul,進行代碼的改造

    <li ng-repeat="todo in todos ">
           <div class="view">
               <input class="toggle" type="checkbox">
                   <label>{{todo.text}}</label>
                   <button class="destroy"></button>
           </div>
           <form>
               <input class="edit" ng-model="todo.text">
           </form>
       </li>
  • 添加功能的實現:

    • 判斷輸入的文本是否爲空,爲空不作處理

    • 對todos作push操做添加元素,添加後將input文本框變爲空,添加的元素須要三個屬性:id,text,completed

    • 考慮id不能重複的問題使用Math.random()取隨機數進行id的生成,具體實現代碼以下:

      function getId() {
             var id = Math.random();
             for (var i = 0; i < $scope.todos.length; i++) {
                 if ($scope.todos[i].id === id) {
                     id = getId();
                     break;
                 }
             }
             return id;
         }
         $scope.add = function () {
            if (!$scope.text) {
                return;
            }
            $scope.todos.push({
                id: getId(),
                text: $scope.text,
                completed: false
            });
            $scope.text = "";
        }; 
        <form ng-submit="add()">
            <input class="new-todo" placeholder="What needs to be done?" ng-model="text" autofocus>
        </form>
  • 刪除功能的實現

    • 暴露方法

      $scope.remove = function (id) {
            for (var i = 0; i < $scope.todos.length; i++) {
                if ($scope.todos[i].id === id) {
                    $scope.todos.splice(i, 1);
                    break;
                }
            }
        };
    • 添加使用

      <button class="destroy" ng-click="remove(todo.id)"></button>
  • 清空功能的實現

    • 暴露方法

      $scope.clear = function () {
            var result = [];
            for (var i = 0; i < $scope.todos.length; i++) {
                if (!$scope.todos[i].completed) {
                    result.push($scope.todos[i]);
                }
            }
            $scope.todos = result;
        };
    • 添加使用

      <button class="clear-completed" ng-click="clear()">Clear completed</button>
  • 對清空功能添加限制,在有選中的時候顯示,沒有的時候隱藏

    • 暴露方法

      $scope.existCompleted = function () {
            for (var i = 0; i < $scope.todos.length; i++) {
                if ($scope.todos[i].completed) {
                    return true;
                }
            }
            return false;
        };
    • 添加使用

      <button class="clear-completed" ng-click="clear()" ng-show="existCompleted()">Clear completed</button>
  • 添加編輯

    • 暴露方法

      $scope.currentEditingId = -1;
       $scope.editing = function (id) {
           $scope.currentEditingId = id;
       };
       $scope.save = function () {
           $scope.currentEditingId = -1;
       };
    • 添加使用

      <label ng-click="editing(todo.id)">{{todo.text}}</label>
       <form ng-submit="save()">
           <input class="edit" ng-model="todo.text">
       </form>
  • 添加所有選中功能

    • 暴露方法

      var now = true;
             $scope.toggleAll = function () {
                 for (var i = 0; i < $scope.todos.length; i++) {
                     $scope.todos[i].completed = now;
                 }
                 now = !now;
             };
    • 添加使用

      <input class="toggle-all" type="checkbox" ng-click="toggleAll()">
  • 添加過濾功能

    • 暴露方法

      $scope.selector = {};
        $scope.$location = $location;
        $scope.$watch('$location.path()', function (now, old) {
            
            switch (now) {
                case '/active':
                    $scope.selector = {completed: false};
                    break;
                case '/completed':
                    $scope.selector = {completed: true};
                    break;
                default:
                    $scope.selector = {};
            }
        });
        $scope.equalCompare = function (source, target) {
            
            return source == target;
        };
    • 添加使用

      <li ng-repeat="todo in todos |filter:selector:equalCompare" ng-class="{completed:todo.completed,editing:todo.id===currentEditingId}"></li>
            <ul class="filters">
                <li>
                    <a ng-class="{selected:selector.completed==undefined}" href="#/">All</a>
                </li>
                <li>
                    <a ng-class="{selected:selector.completed==false}" href="#/active">Active</a>
                </li>
                <li>
                    <a ng-class="{selected:selector.completed==true}" href="#/completed">Completed</a>
                </li>
            </ul>
  • 最後的優化

    <span class="todo-count"><strong>{{todos.length}}</strong> item left</span>

第一次優化-使用路由

  • 使用angular的路由組件,在終端進入todomvc-app-template目錄,輸入如下命令:

    npm install angular-route --save
  • 在index.html 添加引用

    <script src="node_modules/angular-route/angular-route.js"></script>
  • 配置路由

    var myApp = angular.module('MyTodoMvc', ['ngRoute']);
         myApp.config(['$routeProvider', function ($routeProvider) {
             $routeProvider.when('/:stauts?', {
                 controller: 'MainController',
                 templateUrl: 'main_tmpl'
             }).otherwise({redirectTo: '/'});
         }]);
  • 配置app.js

    $scope.selector = {};
    
           var stauts = $routeParams.stauts;
           switch (stauts) {
               case 'active':
                   $scope.selector = {completed: false};
                   break;
               case 'completed':
                   $scope.selector = {completed: true};
                   break;
               default:
                   $route.updateParams({stauts:''});
                   $scope.selector = {};
           }

第二次優化-分模塊

  • 進行分模塊使用

  • 將上面優化後的代碼,進行分模塊處理,即:controller模塊、service模塊。

  • 添加本地存儲

在線展現

http://www.lovefoods.top/todomvc/indexV3.html

源碼下載

https://github.com/guoshiqiufeng/todomvc-app

效果展現

image
image
image
image

相關文章
相關標籤/搜索