Angular principle and module introduction

Source: Internet
Author: User
Tags constructor emit inheritance object model

I front-end small white, but in the company to do a PC-side program, with angular write, had to self-taught a angular frame. Although in the course of work reluctantly enough, but think that since the use of a little to understand a little more comprehensive, so spent a few nights to see the angular developer guide, probably know a little bit angular this east what is dry, and then spent a few nights to do a little record, Prevent later forget.

Angular profile (big God can skip)

Angular is a powerful front-end framework that is powerful in that it can bind static pages to Dynamic data. Usually we see the page interface above the data are fixed, but if we want to change this data, such as I in a text box input, to change a text in real time, swollen broken. There are two ways of doing this (I only think of two, asking the great God to tell more):

1. Change, just request the backend, such as PHP, and then back end back to return a good page, of course, this method is very silly, change a little bit of data on the request back end, it is really silly (because the front-end small white, I used this way to do a small site, and then contact angular only to find himself too silly)

2. Rewrite the DOM through JS (for small white: Here the DOM can be understood as HTML, but the official call Document Object model, small white I always do not know what this is), JS original document class Can do this thing, Then there is a jquery (JS of a powerful library), can also easily rewrite the DOM, for these front-end can know the data will not need to request the backend.

jquery is also just a library that provides some simple ways to change the DOM, which is enough for simple small projects. But for larger projects, not only is the implementation of the feature, but also the maintenance extensible, which requires the MVC pattern (for small white: As for what is MVC, you can see the spring framework that I introduced in the blog). If the logic of using only Jquery,view is mixed with the logic of c,m, it is inconvenient to maintain, for example, you have a text in the TextBox, you have to write code to get the value, then do the processing, or you have a value change, you have to write code to update the view, and angular is the framework for providing such a solution (there will also be a strong sense of angular in the back).

Angular inside the HTML file is the view, called template, when your data changes need to change the template, no more JS code inside to change, you can do nothing, because the angular magical place is the template and data binding binding), the template automatically changes when the data is changed, and your view changes (entering something in the text box) will automatically reflect your data, which is two-way binding. In the concept of angular, the template is a sketch, the data is the color, you want to finish this painting, just want to fill the template you want to color on the line (that is, fill your data), such as the following example, your input automatically displayed to the interface

Http://www.runoob.com/try/try.php?filename=try_ng_intro

You just need to focus on your data and template is enough, how they fill, angular to do this, that is, stripped of the view layer on the Contorller,mdoel layer of influence, the following is the angular official given the difference

General processing data:


Angular


Referenced from: https://docs.angularjs.org/guide/databinding

In short, you use angular data and view automatic two-way binding, without you to update the code, do not angular you have to write your own code in the view changed time to update the data, when the data changed to update the view.

Angular principle

Angular is a frame based on JS, first need to understand how JS works.

JS principle

There is an event queue in the browser, the user triggers something, or a network request, a delay operation (such as a timer), is an event, the browser will rotation these events, and then invoke these callbacks (the callback here is simply understood to trigger a function), Then execute (JavaScript context) into the JavaScript environment, where you can change the data, manipulate the DOM (that is, the HTML structure), and then exit the JavaScript environment and enter the browser environment. The browser then redraws the interface based on the previous changes, which is a process.

The following figure is an official explanation of angular (quoted from Https://docs.angularjs.org/guide/scope)

Angular principle

Angular's operation is in the JavaScript context itself to achieve a set of environment, called angular environment (angular context), non-angular part of the environment called the Classic Environment (classical context),

There is also a queue inside the angular context, which is a watch list that contains the variables that are being monitored, including those that are bound by the data (that is, those that are bound to the view). If the user changes a view that is bound to the data, it triggers a angular function $apply (that is, the event is placed in the event queue and then rotation to this), and then the changed value is updated into the bound variable. Then start calling a digest function, Digest is used to rotation this watch list, see whether the list of changes, if there is a change in the change to rewrite the corresponding Dom (not angular to write this part of the code yourself, if you have 100 variables, You'll have to write 100 of these changes, and if you change later, you have to refactor yourself.


Some references to the angular principle mechanism:

http://www.cnphp6.com/archives/64167

Http://www.tuicool.com/articles/fAfiMv

Here are two more points to note,

1.angular will rotation at least two times watch list, why. Because the first rotation may trigger changes in other watch lists when the DOM is rewritten, it will be rotation again until the variable rotation twice in a row is no longer changed. So if you have two variables change is mutual influence, is a change trigger b change, B changed to trigger a change, this will cause the cycle of death, angular seems to be in rotation 5 times (or 10 times, I forget), if also found that the value is not stable, will error (I have done, the interface suddenly stuck dead, The entire browser is stuck, finally open the console to see, all is angular rotation report of the fault, angular rotation directly to die the entire browser).

2. In addition, on the issue of efficiency, it has been suggested that angular such an undifferentiated rotation may affect performance, but the founder of Angular explained that people can see up to 200 elements on a single page, there are not so many elements bound data on a Web page, If binding so many elements need to be updated in real-time, that is the problem of Web design (quoted StackOverflow, the specific URL can not be found), so do not worry about the efficiency of rotation, if there is a real efficiency problem, the page itself may have problems (see a post on the watercress, A person with angular measured 500 ngmodel bound page, very card, so for unnecessary binding, preferably not tied)

Angular components

Controller

Controller is an important component of angular, the basic use of angular will definitely use the controller. The controller, as its name implies, is the C, logical control of MVC. In angular, the controller is a JavaScript constructor that has two functions, initializes the scope, and adds a method (add behavior).


Citation: Https://docs.angularjs.org/guide/controller

Here is a little bit of a brief explanation of scope (which is said later) that scope is an object that can be understood as a bridge between view and controller, there are some values in the properties of scope, there are some methods (behavior), In the HTML can be directly accessible to, as shown below, the Ng-click inside the methods are a property of the scope, as well as the values displayed. After initializing within scope, the values can be accessed within the view (that is, HTML, angular is officially called template), or it can trigger these methods, which is the use of angular data bidirectional binding (very simple, Don't write a bunch of jquery.)

Citation: Https://docs.angularjs.org/guide/controller

So the controller is what it says, initializing scope and adding a method to scope, while angular also gives some non-recommended ways (see figure below), because there's basically a better way to do this.

Citation: Https://docs.angularjs.org/guide/controller

Tips:

1. Angular after the 1.2 version of a controlleras syntax, this syntax allows the controller to be an individual name (there is wood feel like SQL inside as), as shown below


If you do not use this syntax, you need to be in the controller of the function of the dependency injection (Dependency injection, the following will be introduced, as shown in the above example, in the parameters of the function to write a $scope). If this syntax is not used, the difference between the two is not the controller as this syntax, HTML access to the scope of the property to access the data, so the HTML access to the data into the scope of the properties, if the controller as, The entire controller instance (demo in the example) acts as a property of scope, such as the value of the HTML to access a data property

Controller as accesses the Scope.demo.data

Controller is visiting Scope.data.

2. Controller inheritance, each controller inheritance is actually the inheritance of scope, can be simply understood as the inheritance of JavaScript, can be seen in my other blog (if there is time to t^t), or angular official documents said above. In this case, if the child controller does not specify this data, it will be used in the parent class, if specified by the subclass, but note that if it is changing the value inside the model, it is possible to change the value of the parent class (the concept is also described below)

Service

Service can be understood as the M layer in the MVC structure, to deal with the specific business logic, the most ideal code is to trigger the controller in the view of the function, and then the controller to invoke the model inside the specific processing, The model then returns the data to the controller to change the scope, which is reflected on the view. Service is the function, in angular, service has two characteristics

1. Lazy Loading (lazy loading): This service instance is generated only when it is needed (that is, when an injection is dependent on another service,filter,directive or controller)

2. Singleton mode (singleton): Service in Angular is a singleton (singleton), only the first time when injected to create an instance, and then exist in the cache, and so on when needed (that is, another dependency injection time), removed from the cache. So the life cycle of a service is always there, unless the app exits, as long as it is created. Can not be destroyed (I have not found a method of manual destruction, in fact, on the Internet to find some examples of the need to destroy, in fact, can be done in other ways, not necessarily to destroy the service instance)

Http://stackoverflow.com/questions/32781488/how-to-destroy-an-angular-factory-instance

PS: If you need more examples in the process of use, you can make a slight change, the service as a Factory mode, return all the necessary instances. You can refer to the following connection (two examples in fact, just a little different in the wording of the service, in addition to the hint link inside the page in the Embed tab bar can see the style)

http://jsfiddle.net/rbdmjLok/3/

http://jsfiddle.net/jeremylikness/rbdmjLok/

Sign up for service

In the official developerguide inside the main introduction of two ways, Factory mode and provider mode, but there is a service mode, so there are a total of three kinds:

1. Factory: Angular inside a more commonly used way, register a function, this function will be called when the instance is generated, which returns a service instance (to write the return itself), So just write the service you need to be a obj, define the method and value in this obj, and then return this obj again, as shown below

2. Service: Service registration is simpler, equivalent to a layer of encapsulation of factory. Just write the required method and value in the service, do not need return, as shown below

3. Provider: Provider is the angular inside the registration service the bottom way, whether it is the service mode registration or factory registration, in fact, the bottom is used provider this way. In the provider there is a $get attribute, this property is a function, this function is factory inside we write that function, with service that writing here is new A service of that function assigned to it (JS inside function can also be regarded as an object, so it is equivalent to a direct new object to $get), angular is by the dependency injection (described later), call this function to obtain an instance.

If a service only knows a configuration before instantiating it, such as reading a file or some dynamic configuration of a network return, this cannot be written in the code, it needs to pass parameters to the service initialization (a bit similar to the Java,c++ constructor with parameters), This time it needs to be configured inside the provider. So provider is to do some configuration of the service before the service initialization component (so called provider), in the provider to leave an interface (that is, to leave a function), and so get to the desired configuration when the provider of this interface, You can set the parameters for the service. Note: The provider here just provides a way to interpret it as a tool, and Config is the thing to call provider. As for why not directly with the provider call, but also add a config, I started to think, and then asked my boss, he thought it was just for good understanding, let a person see is configured. Later, I also thought about it, should also be for the convenience of unified configuration. If the direct provider built inside, either write separately, or also write a function in the inside configuration, angular presumably should be to provide a unified and easy to understand the interface bar (personal understanding). The specific example is as follows (note: the name written in provider will be appended with a provider after the name, such as the user written in the example, but the provider that is actually called is Userprovider)

In any of the above three ways, the official document does not seem to give much obvious advice, as the individual thinks, the service is more inclined to a services, factory in favor of a tool, provider need to do some configuration for this service. The following blog is well written, there is also a description of when to use which mode, attached some reference.

https://my.oschina.net/tanweijie/blog/295067 (above a few figures refer to this)

Https://docs.angularjs.org/guide/services

Http://stackoverflow.com/questions/15666048/angularjs-service-vs-provider-vs-factory?rq=1

Scope

Scope is a bridge between controller and view, as angular officially describes: Scopeis the glue between application controller and the view (as shown in the example above)

Scope External API:

Scope mainly provides three external APIs (only two are mentioned in the Official Document developer guide)

1.watch:

Monitor if the model has changed, note that watch here provides three API listeners

(1) (scope. $watch (watchexpression, Listener)): Only listen for the corresponding value or reference change, if the change triggers the registered callback function (that is, the listener)

(2) (scope. $watchCollection (watchexpression, listener)): Listen for the corresponding value or reference and whether the collection changes (for example, the collection increases or decreases, but does not include the value changes inside the collection)

(3) (scope. $watch (watchexpression, Listener, True)): Listen to the corresponding value or reference and whether the change in the collection and also include the value of the change, the following figure can be clearly seen in the difference between

2.apply:

Release the model change message outside the angular context (PS: If the angular is not updated in the angular context, for example, the model is updated in settimeout this way, Because settimeout just put an event into the queue, not immediately execute, wait until the function of registration timeout, if it is completely unrelated to the angular, that is, there is no use of angular some of the built-in commands, This is not triggered into the angular context, so this time the run is completely outside the angular context, so even if the model data is updated, it will not be displayed on the view above, so to update in the outside general to call on their own apply, For specific examples, refer to the blog below. Apply is automatically called in the command that starts with NG and some of the service that angular comes from, so we don't need to call it.

3.digest:

This is not listed in the official angular document, but it can also be called directly, the official should not recommend this. Calling apply will call Digest,digest rotation those watches (the list of those values that registered the listener), and if the value changes, it will call the function of Watch registration to do some processing, which can be understood as apply->digest- >watch

Reference from: http://www.cnphp6.com/archives/64167

Scope category

Scope is divided into two types, one is child scope, one is Isolatescope, the former is based on similar DOM structure inheritance, the latter is completely independent (generally used in directive, because directive is generally out of context, can be used alone, For example, to make a generic list, in use only need to pass a list of values to come in, this is not context-independent, so generally independent, similar to Android inside the same adapter)

Scope Inheritance

For the child scope inheritance, and JavaScript inheritance is almost, simply speaking, if the sub-scope does not have attributes, will go to the parent scope to find, one layer to find.


If you want to assign a value at this time, you will not change to a property in the parent scope, such as Parentscope.a= 1, if Childscope does not specify a then Childscope.a is also 1, but if the assignment is Childscope.a = 2, this time parentscope.a or 1, why, because the assignment statement for JavaScript is not a change of value of the statement, is to create a childscope for the property value of a is equal to 2, so the parent PARENTSCOP is not affected. But if the property is a model (that is, the object) is not the same, thought to access the model when the reference (this is not the same as C + +, Java and JavaScript are the class as reference, C + + is a copy of a copy of the constructor, unless the copy constructor is modified, otherwise the default is a pass value), for example: Parentscope.a.value = 1, if Childscope is not specified, Then Childscope.a.value is also 1, when the assignment Childscope.a.value = 2, then the parent parentscope.a.value is also 2. Why, because Childscope.a is the property that accesses Parentscope (if not specified in Childscope, note this premise), because A is a model (object), so the address is accessed (reference), this time a.value= 2 is the value of this address is rewritten, so Parentscope will also be changed. Of course, if the first Childscope.a=newa, so Childscope point is not parentscope, then change a value will not affect the parentscope. It is recommended that you try it in your console (JavaScript is actually a class, and my other blog also describes the inheritance of JavaScript and angular).

Reference from:

Https://github.com/angular/angular.js/wiki/Understanding-Scopes

Https://docs.angularjs.org/guide/scope

Track Scope

This is the official angular. How to debug scope in view, that is, to see some of the current values of scope

In fact, there is another way, that is, we use a method in the project, set a global variable, and then each controller inside the scope assigned to the global variable, so that in the console from within the global variable to see the value of the scope to be traced. But note: If this global variable is only for debugging, do not use this global variable in code, that is, do not read, because this existence is only used as debugging, is a thing to be removed at any time, if the code logic depends on the value of the global variable, after the removal will lead to error. So don't let the code rely on a variable that will be removed at any time. Scope Event Distribution

This is basically useless in the project, but angular provides this mechanism, emit and broadcast (do Android students should have a sense of the word, but in fact this is similar to the event delivery mechanism of the Android events Dispatch, For example TouchEvent and clickevent this kind, but angular this does not seem to exist the consumption, because the project does not use this, therefore also did not examine carefully, asks the big God to inform)

Emit

Release event, both the current scope and the parent scope can receive this event, if there is a callback in the corresponding scope to register the scope, this callback function will be called.

Broadcast:

Publish the event, the current scope and child scope will receive this event, if there is a callback in the corresponding scope to register the scope, this callback function will be called.

For specific examples, refer to

Https://docs.angularjs.org/guide/scopeScope Events Propagation Section



Dependencyinjection (Dependency injection)

Dependency injection is a thing that is mentioned in many programming languages and frameworks. In fact also very good understanding, first what is dependent, a module (such as class, method), need to use the B module of things, this time said a to B has a dependency, such as a class inside there is an Add method, in class B inside the need to use this Add method, is b to a dependent. This time it is necessary to inject (in fact, injection can also be understood as the initialization of this meaning), in Java may need a new a, in the angular, directly in the form of function parameters to write, but first in other places to define the dependent class, is to define a service (as described in the service section above) and then pass the service as a function parameter. This is the equivalent of a new object. Refer to the example of the service section above or angular official example

There are three types of dependency injection notation in angular:

1.Inline arrayannotation:

In brackets, write in single quotation marks, and in the parameters of the function, and note that the order is consistent.

2. $inject propertyannotation

Use $inject to write, but also pay attention to the same parameter sequence

3.ImplicitAnnotation

Only in function parameters, the simplest kind of writing, but also angular official not recommended. Because this kind of writing in code confusion will be problematic, of course, there is a tool to solve this problem, here is not mentioned, see angular official document Https://docs.angularjs.org/guide/di

In addition, angular also provides a strict mode (Android also has a strict mode, but unlike angular, Android students do not confuse), do not allow implicit Annotation, once used implicit Annotation will be error, here also not introduced, see angular official document ibid. In addition, there are three ways to solve the dependency problem (pictured below), but Angular thinks the first two methods are not good, because the first two have to encode themselves, it is more troublesome, especially in the unit test, so the Third Kind (Spring framework is also used this way), Angular mainly relies on $injector to create and track dependencies, so it relieves the developer of the burden. For more details, refer to angular official documentation, which is not mentioned here.

Template

Angular inside of the template is actually HTML, in the angular, you can use the following four ways to control the display of the template (HTML), are relatively simple, see examples to know, here is not mentioned. Angular suggest that if it is a simple app, you can write all the HTML in the same HTML file, Then use directive these to control (generally is index.html), if the more complex of the app, you can put different view (that is, HTML) in the same page, but the respective view is defined in a different HTML file, and then by reference in the way loaded in this page (Our project is done this way, in fact, it can also be considered a index.html, but many of the view is from other HTML files)


Reference from:

Https://docs.angularjs.org/guide/templates


PostScript: Originally wanted to study carefully angular official document again, but later found that has written more than 6,000 words, put in a not good in the inside, just this is the introduction of angular some basic components, is the basic chapter. Next is just in time to catch up with the company's business adjustment, and now also need to take over the work of other lines of business, the latter may also not have time to write how many JS, so first sent out, but also for the past period of writing a small summary of angular, hope to have a chance to write a sequel to this blog post.


because the predecessors, can be higher

1. Rookie Tutorial: http://www.runoob.com/angularjs/angularjs-tutorial.html (beginner can see this, can quickly master some basic use)

2. Angular Official document Developer Guide:https://docs.angularjs.org/guide/concepts (can be viewed from the concepts of this module, most of this is based on angular Developer guide, mainly from the same website, has been indicated in the article, do not list the references of each module.

3.angular working principle: http://www.cnphp6.com/archives/64167

4.angular working principle: http://www.tuicool.com/articles/fAfiMv

5.stackoverflow about how to destroy service:http://stackoverflow.com/questions/32781488/ How-to-destroy-an-angular-factory-instance (Finally, the answer suggested not to destroy, in fact, can be used in other ways to achieve business logic, here is mainly to explain the fact that many times do not have to destroy the service, Can be done in other ways)

6. How to use the Polymorphic service: http://jsfiddle.net/rbdmjLok/3/(example for a count service, in two places the example of a separate count, a service is used independently of multiple locations)

7.service three different construction methods: https://my.oschina.net/tanweijie/blog/295067

8.service three different construction methods: Http://stackoverflow.com/questions/15666048/angularjs-service-vs-provider-vs-factory?rq=1

Inheritance between 9.JavaScript and angular: https://github.com/angular/angular.js/wiki/Understanding-Scopes (This article is very good, worth reading)


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.