Original address: http://code.angularjs.org/1.0.2/docs/guide/concepts
continue. .
1. Summary
This article mainly provides an overview of angular components and explains how they work. The list is as follows:
2. Startup
Here is how angular is started (see the chart with the following example):
1. The browser loads HTML and converts HTML tags into DOM objects;
2. The browser loads the script of angular.js;
3. Angular waits for the DOMContentLoaded event;
4. Angular looks for ng-app, a directive used to specify the application boundary range;
5. If ng-app has a specified module (perhaps ng-app="SomeApp"), it will be used as configuration $injector;
6. $injector is used to create $compile service (service) and $rootScope;
7. The $compile service is used as a "compile" (kind of like traversal, then do a little mysterious thing) DOM and connect it to the corresponding $rootScope.
8. ng-init This directive creates a name attribute in the corresponding scope and assigns it a "Kitty" value;
9. Insert the value of "{{name}}" into the expression and finally display "Hello Kitty!".
<!DOCTYPE html><html lang="zh-cn" ng-app><head> <meta charset="UTF-8"> <title>Hello Kitty!</title> <style type="text/css"> .ng-cloak { display: none; } </style></head><body><div ng-init="name='Kitty'">Hello {{name}}!</div><script src="../angular-1.0.1.js" type="text/javascript"></script></body></html>The progress was slow because I discussed something with someone tonight. . . That's the sentence again. . . It's late at night now. . . Angular, see you after the ad!
==============================================================
The ad is finished. . . continue
3. Runtime
This chart and the following example describe how angular interacts through the browser event-loop (all time processing functions, as well as the functions executed by timer, will be arranged in a queue structure, and use an infinite loop to continuously extract the functions from the queue to execute. This is event-loop. From http://wiki.nodejs.tw/nodejs_from_scratch/javascript-yunodejs/2-1-event-loop).
1. The browser event-loop waits for the event to arrive. Events come from user interaction (DOM events), timer events (setTimeout), network events (server response, XHR, etc.);
2. The event callback function begins to execute. Here we enter the javascript context (context). This callback function can modify the DOM structure.
3. When the callback function is executed, the browser exits the javascript context and redraws the view according to the DOM changes.
Angular modifys the general javascript flow by creating its own event processing loop. This splits Javascript into traditional and Angular execution contexts. Any operations performed in the Angular execution context have angular data-binding, exception handling, property watching and other abilities. We can enter the Angular execution context by using $apply() in javascript. But remember that in most places (angular) (such as controllers, services), the directive that handles events will call $apply for you. The scenario where $apply is manually called is usually when you implement a custom event handler or handle callbacks from third-party libraries.
1. Enter the angular execution context by calling scope.$apply(stimulusFn). stimulusFn is a function (including scope as an argument) or an angular legal expression that we want to execute in the angular execution context.
2. Angular executes stimulusFn, which usually changes the application state.
3. Angular enters the $digest loop. This loop consists of two smaller loops that handle $evalAsync queue and $watch list. The $digest loop will keep iterating before the model is stable, i.e. the $evalAsync queue is empty, and no changes are detected by the $watch list.
4. $evalAsync queue is used as a means to arrange that the current stack frame must be jumped out of the current stack frame (the stack frame refers to the area (or space) allocated to the currently running function in the stack. The passed parameters, the return address (which must be redirected to when the function ends. Translation Note: that is, the breakpoint of the main call function), and the internal storage unit used by the function (i.e., the local variables stored on the stack) are all in the stack frame. The work outside of the C.1.1 stack frame), but before the browser view is drawn. This is usually achieved by using setTimeout(0). But the method setTimeout(0) will cause slowness, or when the browser draws the view after each event is processed, the view will flash (Is angular solving this problem? How to solve it?).
5. $watch list is a collection of expressions that may be modified in the latest iteration. If (model) changes, the $watch function will be called to achieve the goal of reassigning a specific DOM.
6. Once the Angular $digest loop is completed (the situation mentioned in the previous 3), after leaving the angular and javascript context, the browser will then repaint the DOM in response to the changes.
The following explains how the example "Hello Kitty" (-_-!) implements data-binding effect when the user enters text in the text box.
1. Compilation phase:
a) ng-model and input directive keydown event listeners are specified in <input>.
b) {{name}} placeholder (interpolation, don't know how to translate) (expression) Set a $watch to respond when the name changes.
2. Runtime phase:
a) Press the "X" button in the inut control to let the browser trigger a keydown event;
b) input directive captures the change in the text box value, and then calls $apply("name = 'X';"), updating the applied model in the angular execution context.
c) Angluar applies "name = 'X';" to the model. (The model has changed)
d) $digest loop start
e) $watch list detects that the value of name has been changed, then parses the {{name}} expression again, and then updates the DOM.
f) Angular exit (angular) execution context, and then exit the keydown event and javascript execution context in turn;
g) The browser redraws the view and updates the characters.
<!DOCTYPE html><html lang="zh-cn" ng-app><head> <meta charset="UTF-8"> <title>Hello Kitty!</title> <style type="text/css"> .ng-cloak { display: none; } </style></head><body> <input ng-model="name"/> <p>Hello {{name}}!</p><script src="../angular-1.0.1.js" type="text/javascript"></script></body></html>4. Scope
The scope is responsible for detecting changes in the model and serving as the execution context of the expression. Scope is nested in a hierarchy similar to a DOM structure (as we learned earlier, division may be related to controller). (For details, check the individual directive documentation to see which directive will create a new scope)
The following example shows that the value of the expression "name" is determined based on the scope it depends on (to which it belongs), and also includes the method of value search (similar to Js scope chain, if you don't have it, please look for my dad).
<!DOCTYPE HTML><html lang="zh-cn" ng-app><head> <meta charset="UTF-8"> <title>scope</title> <style type="text/css"> .ng-cloak { display: none; } </style></head><body><div ng-controller="ControllerA"> Hello {{name}}!;</div><div ng-controller="ControllerB"> Hello {{name}}!; <div ng-controller="ControllerC"> Hello {{name}}!; <div ng-controller="ControllerD"> Hello {{name}}!; </div> </div></div><script src="../angular-1.0.1.js" type="text/javascript"></script><script type="text/javascript"> function ControllerA($scope) { $scope.name = 'Kitty'; } function ControllerB($scope) { $scope.name = 'Lclao'; } function ControllerC($scope) { $scope.name = 'Jeffrey'; } function ControllerD($scope) { }</script></body></html>5. Controller
<!DOCTYPE HTML><html lang="zh-cn" ng-app><head> <meta charset="UTF-8"> <title>Controller</title> <style type="text/css"> .ng-cloak { display: none; } </style></head><body><div ng-controller="ControllerA"> Hello {{name}}! <button ng-click="doIt()">DoIt!!</button></div><script src="../angular-1.0.1.js" type="text/javascript"></script><script type="text/javascript"> function ControllerA($scope) { $scope.name = 'Kitty'; $scope.doIt = function() { $scope.name = "Handsome"; }; }</script></body></html>Controller is the code behind the view (-_-!). Its responsibility is to build the model and push it into the view through the callback function. View is the current scope to template (HTML) map (translated a bit barely...). Scope is the link that directs the model to the view and sends event to the controller.
It is important to separate the Controller from the View because:
1.Controller is written in javascript. Javascript is imperative. An important command is a good way to describe the behavior of an application. Controllers should not contain any display information (logical) (DOM references or HTML fragments)
2.View template is written in HTML. HTML is declarative. Declarative (HTML) is a good way to describe a UI. Views should not contain any behavior.
3. Since the controller does not know which View it needs to correspond to, a Controller can (indirectly) use multiple Views. This is important for re-skinning (replace skins?), other device-specific views (such as mobile phones and desktops), and the measurability of code.
6. Model
Model can be understood as a data object. It is used as a combination with the template to produce views. In order to write the model to the view, the model must be referenced by scope. Unlike many other frameworks, angular has no restrictions or requirements on model. There is no need to add an additional class, nor do you need to access or change the model through special privileged methods. The data type of the Model can be a primitive type (string, number...), a key-value object ({a:1,b:2}), or a function (function() {…}). To put it simply, the angular model needs to be a normal javascript object.
7. View
View is something users can see. The view was born in the template. It combines with the model and eventually renders it as a browser DOM. Angular takes a very different way to present the View for many other template systems.
Other template engines: Many template engines are implemented by creating HTML strings with special tags. Usually these template tags destroy HTML syntax, which means that the code cannot be edited through a general HTML editor (this is...). The template string is passed into the template engine and merged with the data. Finally generates HTML string. These strings are generally written to the DOM in .innerHTML, prompting the browser to render the template content. This process needs to be repeated again and again when the data changes. The granularity of the template is consistent with the granularity of the DOM update. The key to this grain is that the template system processes strings.
Angular: The difference between Angular templates is that it is DOM-based rather than string-based. The template still needs to write some strings into the HTML, but it is still HTML (not by embedding the template inside). The browser converts HTML to DOM, and then DOM becomes the input of compiler (angular's template engine). Compiler looks for directives and set watches in the model in turn. The result is a view that has been updated all the time, and there is no need to re-stitch the model and template. Model becomes the only source of truth for view.
8. Directives
Directive is a behavior (for example, in the previous article's example "hide and seek") or DOM conversion (custom tags, containing a set of DOMs), and placing its name in the attribute, tag name, and class name can trigger the directive. Directive allows you to extend HTML tags in a declarative way.
There are still some questions in the following examples. That is how $render triggers @_@
<!DOCTYPE HTML><html lang="zh-cn" ng-app="myDirective"><head> <meta charset="UTF-8"> <title>directive</title> <style type="text/css"> .ng-cloak { display: none; } </style></head><body ng-controller="MyCtrl"><div ng-model="content" contenteditable="true">My Little Dada</div><pre>modelValue = {{content}}</pre><button ng-click="reset()">reset(change model)</button><script src="../angular-1.0.1.js" type="text/javascript"></script><script type="text/javascript"> angular.module("myDirective",[]) .directive("contenteditable",function() { return { require:'ngModel', link:function (scope, element, attr, ngModel) { function setVal() { ngModel.$setViewValue(element.text()); } // veiw -> model element.bind("keyup",function() { scope.$apply(setVal); }); // model -> view ngModel.$render = function(val) { console.log("render running"); element.html(val); }; //init setVal(); } } } ).controller("MyCtrl",function($scope) { $scope.reset = function() { $scope.content = "My Little Dada"; }; });</script></body></html>9. Filters
Filters plays a role in data conversion (formatting). Usually they are related to the region, and different regions may have different output formats. They are following the spirit of Unix filters with similar syntax: | (pipe)
<!DOCTYPE HTML><html lang="zh-cn" ng-app><head> <meta charset="UTF-8"> <title>filter</title> <style type="text/css"> .ng-cloak { display: none; } </style></head><body><div ng-init="list = ['Baidu B','Sogou S','360','3SB']"> Number formatting: 1233211234567 -> {{1233211234567|number}}<br/> Array filtering, and then output through json format: <input ng-model="myFilterText" type="text"/><br/> {{list|filter:myFilterText|json}}<br/></div><script src="../angular-1.0.1.js" type="text/javascript"></script></body></html>10. Modules and the Injector
Injector is a service locator. Each Angular application will have a separate injector. Injector provides a way to find object instances by name. Injector will keep all object instances in the internal cache, so when the same name is repeatedly called, the same object instance is returned. If the object does not exist, it will request the instance factory to create a new instance.
Module is a method of configuring an instance factory of an injector, called a "provider".
// Create a module var myModule = angular.module('myModule', []) // Configure the injector myModule.factory('serviceA', function() { return { // instead of {}, put your object creation here }; }); // create an injector and configure it from 'myModule' var $injector = angular.injector('myModule'); // retrieve an object from the injector by name var serviceA = $injector.get('serviceA'); // always true because of instance cache $injector.get('serviceA') === $injector.get('serviceA'); // trueBut the real cool X of injector is that it can be used to call methods and "instantiate" type. This wonderful feature is that it allows methods and types to request the resources they depend on, rather than searching for them.
// You write functions such as this one. function doSomething(serviceA, serviceB) { // do something here. } // Angular provides the injector for your application var $injector = ...; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// call the function doSomething(serviceA, serviceB); //The above is the traditional old method~The following is the method of angular talking about its own cow X/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// The cool way of getting dependencies. // the $injector will supply the arguments to the function automatically $injector.invoke(doSomething); // This is how the framework calls your functionsNote that the only thing we need to write is our function, and we can list the resource that the method depends on in the arguments of the function! When angular calls function, it will use the "call" method to automatically fill function agruments.
Note how the dependencies are listed in the constructor in the example below. When the ng-controller instantiates the controller, the dependency resources will be automatically provided. There is no need to create, search, or create injector references to load dependency resources.
<!DOCTYPE HTML><html lang="zh-cn" ng-app="timeExample"><head> <meta charset="UTF-8"> <title>injector</title> <style type="text/css"> .ng-cloak { display: none; } </style></head><body><div ng-controller="ClockCtrl"> Current time is : {{time.now}}</div><script src="../angular-1.0.1.js" type="text/javascript"></script><script type="text/javascript"> angular.module("timeExample", []).factory("myClock", function ($timeout) { var time = {}; (function tick() { time.now = new Date().toString(); $timeout(tick, 1000); })(); return time; }); /** * * @param $scope * @param myClock The dependency myClock is automatically inserted here! ! * @constructor */ function ClockCtrl($scope,myClock) { $scope.time = myClock; }</script></body></html>11. Angular Namespace
To prevent name conflicts, angular will add the prefix $ to the object's name. Please do not use $ prefix in your code to avoid conflicts. (-_-!! )
The above is the information about AngularJS concepts. We will continue to add relevant articles in the future. Thank you for your support for this site!