AngularJS Study Notes: TodoMVC analysis _ AngularJS

Source: Internet
Author: User
This article mainly introduces the analysis of TodoMVC, which is used by AngularJS study notes. If you need it, you can refer to AngularJS for a long time.

Official website address: http://angularjs.org/

First, we recommend several tutorials.

1. The AngularJS getting started Tutorial is based on the official Tutorial translation.

2. The seven steps from AngularJS cainiao to experts are also relatively basic, and an online music playing website is created.

3. AngularJS Development guide this tutorial is comprehensive, but I feel that the translation is obscure.

After reading these tutorials, I think AngularJS knows a little about it. If I want to use it to do something, I will analyze todomvc written by AngularJS.

Todomvc official website address: http://todomvc.com/

The project directory is as follows:

There are two folders in bower_components. The angular folder is used like angular. in the js file, the todomvc-common folder contains css \ js (only used to generate content on the left, irrelevant to the project) and images of all todo projects.

The js folder contains the corresponding controller, directive, service, and app. js.

The code used for testing is stored in the test folder without analysis.

Index.html is the view page of the project.

Let's take a look at app. js.

The Code is as follows:


/* Global angular */
/* Jshint unused: false */
'Use strict ';
/**
* The main TodoMVC app module
*
* @ Type {angular. Module}
*/
Var todomvc = angular. module ('todomvc ', []);

Is to define a module todomvc

Let's take a look at todoStorage. js under services.

The Code is as follows:


/* Global todomvc */
'Use strict ';
/**
* Services that persists and retrieves TODOs from localStorage
*/
Todomvc. factory ('todostore', function (){
// Unique todos JSON string storage identifier
Var STORAGE_ID = 'todos-angularjs ';
Return {
// Retrieve todos from localStorage and parse it into a JSON object
Get: function (){
Return JSON. parse (localStorage. getItem (STORAGE_ID) | '[]');
},
// Convert the todos object into a JSON string and save it to localStorage
Put: function (todos ){
LocalStorage. setItem (STORAGE_ID, JSON. stringify (todos ));
}
};
});

The factory method is used to create the todoStorage service method. The essence of this service method is to return two methods get and put, both of which use the JSON2 and HTML5 features. Get retrieves the todos content from localStorage and parses it into JSON. put converts todos into a JSON string and stores it in localStorage.

Let's take a look at the two command files under directives.

TodoFocus. js

The Code is as follows:


/* 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 ('todocs', function todoFocus ($ timeout ){
Return function (scope, elem, attrs ){
// Add a listener for the value of the todoFocus attribute
Scope. $ watch (attrs. todoFocus, function (newVal ){
If (newVal ){
$ Timeout (function (){
Elem [0]. focus ();
}, 0, false );
}
});
};
});

In the return function parameter, elem is an array containing the elements of the command, and attrs is an object composed of all attributes and attribute names of the element.

Two AngularJS methods are used.

$ Watch (watchExpression, listener, objectEquality) registers a listener callback. When watchExpression changes, the listener callback is executed.

$ Timeout (fn [, delay] [, invokeApply]) when the value of timeout is reached, the fn function is executed.

TodoFocus. js creates the todoFocus command. When an element has the todoFocus attribute, this command adds a listener for the value of the todoFocus attribute of the element. If the value of the todoFocus attribute changes to true, $ timeout (function () is executed () {elem [0]. focus () ;}, 0, false); the latency is 0 seconds, so elem [0] is executed immediately. focus ().

TodoEscape. js

The Code is as follows:


/* Global todomvc */
'Use strict ';
/**
* Directive that executes an expression when the element it is applied to gets
* An 'escape 'keydown event.
*/
Todomvc. directive ('todomainscape ', function (){
Var ESCAPE_KEY = 27;
Return function (scope, elem, attrs ){
Elem. bind ('keylow', function (event ){
If (event. keyCode === ESCAPE_KEY ){
Scope. $ apply (attrs. todoEscape );
}
});
};
});

TodoEscape. js creates the todoEscape command. When you press the Escape key, execute the expression attrs. todoEscape.

Take a look at todoCtrl. js in the controllers folder. This file is a little longer and I will directly write comments.

The Code is as follows:


/* 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 ){
// Obtain todos from localStorage
Var todos = $ scope. todos = todoStorage. get ();

// Record the new todo
$ Scope. newTodo = '';
// Record the edited todo
$ Scope. editedTodo = null;
// Execute the method when the todos value changes
$ Scope. $ watch ('todos ', function (newValue, oldValue ){
// Obtain the number of unfinished todos
$ Scope. remainingCount = filterFilter (todos, {completed: false}). length;
// Obtain the number of completed todos instances
$ Scope. completedCount = todos. length-$ scope. remainingCount;
// When and only when $ scope. remainingCount is 0, $ scope. allChecked is true
$ Scope. allChecked =! $ Scope. remainingCount;
// When the new value and old value of todos are not the same, the todos is stored in localStorage.
If (newValue! = OldValue) {// This prevents unneeded cballs to the local storage
TodoStorage. put (todos );
}
}, True );
If ($ location. path () = ''){
// If $ location. path () is empty, set it/
$ Location. path ('/');
}
$ Scope. location = $ location;
// Execute the method when the value of location. path () Changes
$ Scope. $ watch ('location. path () ', function (path ){
// Obtain the status filter.
// If path is '/active', the filter is {completed: false}
// If path is '/completed', the filter is {completed: true}
// Otherwise, the filter is null.
$ Scope. statusFilter = (path = '/activity ')?
{Completed: false }: (path = '/completed ')?
{Completed: true}: null;
});
// Add a new todo
$ Scope. addTodo = function (){
Var newTodo = $ scope. newTodo. trim ();
If (! NewTodo. length ){
Return;
}
// Add a todo to todos. The default value of the completed attribute is false.
Todos. push ({
Title: newTodo,
Completed: false
});
// Leave it empty
$ Scope. newTodo = '';
};
// Edit a todo
$ Scope. editTodo = function (todo ){
$ Scope. editedTodo = todo;
// Clone the original todo to restore it on demand.
// Save the todo before editing to prepare for resuming editing.
$ Scope. originalTodo = angular. extend ({}, todo );
};
// Todo edited
$ Scope. doneEditing = function (todo ){
// Leave it empty
$ Scope. editedTodo = null;
Todo. title = todo. title. trim ();
If (! Todo. title ){
// If todo's title is empty, remove the todo
$ Scope. removeTodo (todo );
}
};
// Restore todo before editing
$ Scope. revertEditing = function (todo ){
Todos [todos. indexOf (todo)] = $ scope. originalTodo;
$ Scope. doneEditing ($ scope. originalTodo );
};
// Remove todo
$ Scope. removeTodo = function (todo ){
Todos. splice (todos. indexOf (todo), 1 );
};
// Clear the completed todos
$ Scope. clearCompletedTodos = function (){
$ Scope. todos = todos. filter (function (val ){
Return! Val. completed;
});
};
// Mark all todo states (true or false)
$ Scope. markAll = function (completed ){
Todos. forEach (function (todo ){
Todo. completed = completed;
});
};
});

At the very bottom, index.html is used for analysis.

The Code is as follows:







AngularJS • TodoMVC






Todos




Mark all as complete




  • {Todo. title }}







{RemainingCount }}




  • All


  • Active


  • Completed


Clear completed ({completedCount }})



Double-click to edit a todo


Credits:
Http://twitter.com/cburgdorf & quot;> Christoph burgddorf,
Http://ericbidelman.com & gt; Eric Bidelman,
Http://jacobmumm.com "> Jacob Mumm and
Http://igorminar.com "> Igor Minar


Part of http://todomvc.com "> TodoMVC



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.