AngularJS 학습 노트 의 TodoMVC 분석
홈 페이지 주소:http://angularjs.org/
먼저 몇 개의 강 좌 를 추천 하 다.
1. AngularJS 입문 강 좌 는 비교적 기본 적 이 고 공식 Tutorial 의 번역 입 니 다.
2. 7 단 계 는 AngularJS 초보 부터 전문가 까지 비교적 기초 가 되 어 온라인 음악 재생 사 이 트 를 만 들 었 다.
3. AngularJS 개발 안내 서 는 비교적 전면적 이지 만 번역 이 좀 어렵 고 이해 하기 어렵다 고 생각 합 니 다.
이 튜 토리 얼 을 보고 AngularJS 도 조금 알 것 같 아서 일 을 좀 하려 면 AngularJS 가 쓴 todomvc 를 분석 해 보 세 요.
Todomvc 홈 페이지 주소:http://todomvc.com/
항목 의 디 렉 터 리 는 다음 과 같 습 니 다.
bower_components 에 두 개의 폴 더 가 들 어 있 습 니 다. 그 중에서 angular 폴 더 는 angular. js 파일 과 같은 것 입 니 다. todomvc - comon 폴 더 에 모든 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 를 정의 한 것 입 니 다.
서비스 에 있 는 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 를 되 돌려 주 는 것 입 니 다. 둘 다 JSON 2 와 HTML 5 의 특성 을 사 용 했 습 니 다.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 함 수 를 실행 합 니 다.
todo Focus. js 에서 todo Focus 명령 을 만 들 었 습 니 다.한 요소 가 todo Focus 속성 을 가지 고 있 을 때 이 명령 은 이 요소 의 todo Focus 속성의 값 에 감청 을 추가 합 니 다. todo Focus 속성의 값 이 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); 
  
             } 
  
         }); 
  
     }; 
  
 }); 
  
 
   todo Escape. js 에서 todo Escape 명령 을 만 들 었 습 니 다.Escape 키 를 눌 렀 을 때 attrs. todo Escape 표현 식 을 실행 합 니 다.
큰 머리 를 보 세 요. 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 를 보 세 요. 이 파일 은 우리 가 한 단락 한 단락 분석 합 니 다.
 
  
  
  
  
  
      
  
          
  
          
  
         AngularJS • TodoMVC  
  
          
  
          
  
      
  
      
  
          
  
              
  
                 todos 
  
                 
 
  
               
  
              
  
                  
  
                  
  
                  
  
                     -  
  
                          
  
                              
  
                              
  
                              
  
                          
  
                       
  
                 
 
  
               
  
              
  
           
  
          
  
          
  
           
  
           
  
           
  
           
  
           
  
           
  
      
  
  
  
 
    우선 맨 아래 에 해당 하 는 JS 를 도입 하 는 것 은 더 말 할 나 위도 없다.
 
  
   
  
   
  
   
  
   
  
   
  
   
  
   
  
 
   style [ng - cloak] 을 정의 합 니 다. ng - cloak 속성 을 포함 하면 보이 지 않 습 니 다.
 
  
  
  
 
   todo 를 추가 하 는 html 를 보 겠 습 니 다. 바 인 딩 된 model 은 new Todo 입 니 다. submit 방법 은 todoCtrl. js 의 addTodo () 입 니 다. todo 를 추가 하고 Enter 를 누 르 면 제출 이 벤트 를 기본 으로 터치 하면 addTodo () 방법 이 실 행 됩 니 다. todo 를 todos 에 추가 합 니 다.
 
  
  
  
 
   todos 를 보 여 주 는 html 를 다시 봅 니 다.
 
  
  
  
      
  
      
  
      
  
         -  
  
              
  
                  
  
                  
  
                  
  
              
  
              
  
           
  
     
 
  
   
  
 
   section 은 ngShow 방법 을 사용 하여 todos 의 길이 에 따라 표시 여 부 를 판단 합 니 다. 게다가 ng - cloak 속성 은 처음에 AngularJS 가 처리 되 지 않 은 페이지 를 표시 하지 않 기 위해 서 입 니 다.새로 고침 을 없 애고 해 볼 수 있 습 니 다.
이 중 id 는 toggle - all 의 checkbox 로 allChecked model 에 연결 되 어 있 으 며, markAll (allChecked) 을 누 르 면 allChecked 의 값 을 입력 하여 모든 todos 를 표시 합 니 다.
ngRepeat 순환 을 사용 하여 li 라벨 을 만 듭 니 다. todo in todos | filter: status Filter track by $index, todos 순환, status Filter 로 걸 러 내 고 $index 로 추적 합 니 다.ngClass 는 두 개의 class 를 연결 하 였 습 니 다. {completed: todo. completed, editing: todo = = edited Todo}, todo. completed 가 true 이면 completed class 를 추가 하고 todo = = edited Todo 이면 editing class 를 추가 합 니 다.class 는 toggle 의 checkbox 를 todo. copleted 에 연결 합 니 다.todo 제목 이 보 여 주 는 label 은 이 벤트 를 더 블 클릭 하여 editTodo (todo) 를 터치 합 니 다. editTodo 는 todo 를 editedTodo 에 부여 한 다음 에 아래 form 의 todo Focus 명령 을 실행 합 니 다. 이때 form 의 input 를 볼 수 있 습 니 다.Esc 를 누 르 면 revert Editing (todo) 을 터치 하고 편집 전 으로 복원 하 며 Enter 를 누 르 거나 초점 을 잃 으 면 done Editing (todo) 을 터치 하여 편집 한 todo 를 저장 합 니 다.class 는 destroy 의 button 에 click 이 벤트 를 연결 하고 removeTodo (todo) 를 누 르 면 이 todo 를 삭제 합 니 다.
마지막 으로 todos 의 통계 정 보 를 보 여 주 는 html
 
  
  
  
 
   ng - pluralize 탭 은 remainingCount 개수 가 1 일 때 item left 를 표시 합 니 다. 그렇지 않 으 면 items left 를 표시 합 니 다.
id 가 filers 인 ul 탭 에 location. path () 의 내용 에 따라 태그 가 다른 a 탭 이 선택 되 었 습 니 다.
id 는 clear - completed button 에 클릭 이 벤트 를 추가 하고 clearComplete Todos () 를 터치 하여 완 료 된 todo 를 모두 제거 합 니 다.
오늘 의 필 기 는 여기까지 하 겠 습 니 다. 모두 개인 적 인 소감 입 니 다. 친구 들 이 좋아 하 기 를 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.