Angular.js Learning road 1: use angular.js Implementation of todomvc

Time:2021-3-3

Knowledge needed

HTML, JS, preliminary understanding angularjs
Familiar with NPM, GIT operation

start

  • A todomvc template is provided on GitHub. We can clone it and use it

  • Install NPM and Git

  • Create a new folder todomvc locally, open the terminal, enter the current directory, and execute the following command

      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
  • This project template is ready to build

realization

  • Open directory with development tool

  • open index.html , add at the bottom of < body > angular.js Reference to

     <script></script>
  • open app.js Replace the window object with angular object, and the code structure is as follows:

    (function (angular) {
        'use strict';
    })(angular);
  • Create a module:

     var myApp = angular.module('MyTodoMvc', []);
  • Create a controller

     myApp.controller('MainController', ['$scope', function ($scope) {
     };
  • Expose text to page

     $scope.text = "";
  • Expose todos to page

    $scope.todos = [
           {
               id: 1,
               Text: 'learning',
               completed: false
           },
           {
               id: 2,
               Text: 'sleep',
               completed: false
           },
           {
               id: 3,
               Text: 'knock code',
               completed: true
           }
       ];
  • stay index.html Find the UL that shows the data in, leave one UL, delete the rest UL, and transform the code

       <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>
  • The implementation of the added function:

    • Judge whether the input text is empty, and do not process if it is empty

    • Push todos to add elements. After adding, the input text box will be empty. The added elements need three attributes: ID, text and completed

    • Consider the problem that ID cannot be used repeatedly Math.random () take random number to generate ID. the specific implementation code is as follows:

         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>  
  • Implementation of delete function

    • Exposure methods

        $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;
                }
            }
        };
    • Add use

            <button class="destroy" ng-click="remove(todo.id)"></button>
  • Realization of clearing function

    • Exposure methods

       $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;
        };
    • Add use

         <button class="clear-completed" ng-click="clear()">Clear completed</button>
  • Add restrictions on the emptying function, which will be displayed when it is selected and hidden when it is not

    • Exposure methods

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

        <button class="clear-completed" ng-click="clear()" ng-show="existCompleted()">Clear completed</button>
  • Add edit

    • Exposure methods

       $scope.currentEditingId = -1;
       $scope.editing = function (id) {
           $scope.currentEditingId = id;
       };
       $scope.save = function () {
           $scope.currentEditingId = -1;
       };
    • Add use

       <label ng-click="editing(todo.id)">{{todo.text}}</label>
       <form ng-submit="save()">
           <input class="edit" ng-model="todo.text">
       </form>
  • Add all selected functions

    • Exposure methods

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

             <input class="toggle-all" type="checkbox" ng-click="toggleAll()">
  • Add filtering function

    • Exposure methods

        $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;
        };
    • Add use

            <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>
  • Final optimization

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

First optimization – using routing

  • Using angular’s routing component, enter todomvc app template directory at the terminal and enter the following command:

         npm install angular-route --save
  • stay index.html Add reference

         <script></script>
  • Configure routing

         var myApp = angular.module('MyTodoMvc', ['ngRoute']);
         myApp.config(['$routeProvider', function ($routeProvider) {
             $routeProvider.when('/:stauts?', {
                 controller: 'MainController',
                 templateUrl: 'main_tmpl'
             }).otherwise({redirectTo: '/'});
         }]);
  • to configure 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 = {};
           }

Second optimization – sub module

  • Carry out sub module use

  • The above optimized code is processed by modules, namely: controller module and service module.

  • Add local storage

Online display

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

Source code download

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

Effect display

Angular.js Learning road 1: use angular.js Implementation of todomvc
Angular.js Learning road 1: use angular.js Implementation of todomvc
Angular.js Learning road 1: use angular.js Implementation of todomvc
Angular.js Learning road 1: use angular.js Implementation of todomvc