web123456

Introduction to angular principles and modules

I front-end white, nay in the company is doing a PC program, using theangularI had to learn a little bit about the angular framework. Although in the process of work barely barely enough, but I think that since I used a little bit more comprehensive understanding, so I spent a few nights to look at the angular developer guide, probably know a little bit of angular this thing in the end what to do, and then spent a few nights to do a little record, to prevent the future forget.

 

Introduction to Angular (the big guns can be skipped)

Angular is a powerful front-end framework that can bind static pages to dynamic data. Normally we see the web interface above the data are fixed, but if we want to change the data, for example, I entered in a text box, to change a text in real time, how to break. At this time there are two ways (I only think of two, please tell the gods more):

1. change a little, then request the back-end, such as php, and then the back-end to re-return to an updated page, of course, this method is very silly, change a little bit of small data on the request of the back-end, it is indeed too stupid (due to the front-end of the little white, I have used this way to do a small site, and then contact angular only to find out that they are too stupid);

2. through the js rewrite DOM (for white: here the DOM can be understood as html, but the official name is called document object model, white I always do not know what this is), js initial document class can do this, and later appeared ajquery(a powerful library for js), it is also easy to rewrite the DOM, and you don't have to request the backend for data that is known on the frontend.

jquery is also just a library that provides some simple ways to change the DOM, for a simple small project is enough. But for a relatively large project, the consideration is not only the realization of the function, but also includes maintainable and scalable, which requires the MVC model (for white: as for what is MVC, you can see my introduction to the spring framework of that blog inside). If you only use jquery, the logic of the view will be mixed with the logic of the c, m, not easy to maintain, for example, you data in the text box of a thing, you have to write code to get the value, and then do the processing, or one of your value changes, you also have to write code to update the view, and angular is to provide such a solution framework (there will be an introduction). Feel the power of angular).

Angular inside the html file is view, called template (template), when your data changes need to change the template, do not need to change the js code, you can do nothing, because angular magical place is the template and data binding (data binding), when the data change template automatically changed, your view changed (enter something into the text box) will also automatically react to your data, this is a two-way binding. When the data changes, the template automatically changes, and when your view changes (typing something into the textbox), it automatically reacts to your data, which is two-way binding. In angular's concept, the template is a sketch, the data is the color, you want to finish the painting, you just need to fill the template with the color you want (that is to say, fill in your data), for example, the following example, your input is automatically displayed to the interface

/try/?filename=try_ng_intro

You only need to focus on your data and template is enough, how to fill the gap between them, angular to do a good job of these, that is, stripping the view layer on the contorller, mdoel layer of the impact of the following is angular officially given the difference between

General Processing Data:


angular:


Quote from:/guide/databinding

Simply put, you use angular data and view automatic two-way binding, you do not have to code to update, not angular you have to write your own code in the view changed to update the data, in the data changed to update the view.

 

angular principle

angular is a framework based on js, first need to understand how js works.

JS Principle

Inside the browser there is an event queue, the user triggers something, or a network request, a delayed operation (e.g., a timer or something like that), it's all an event, the browser will rotate these events and then call these callbacks (the callbacks here can be understood simply as triggering afunction (math.)), and then it goes into theJavaScriptThe process is a process where you can change the data, manipulate the DOM (i.e., the html structure), and then exit the JavaScript environment and enter the browser environment, and then the browser redraws the interface based on the previous changes.

The following is the official angular explanation (quoted from/guide/scope  )

angular principle

angular operation is in the JavaScript context of their own implementation of a set of environments, called angular environment (angular context), non-angular part of the environment is called the classic environment (classic context).

In angular context, there is also a queue, inside this queue is a watch list, the list is loaded with variables that are being listened to, including those that are data bound (that is, those that are bound to the view). If the user changes a data-bound view, an angular function $apply is triggered (which puts the event in the event queue and triggers it when it's time to train it), which updates the changed value into the bound variable, and then calls a digest function, which is used to train the watch list. used to rotate the watch list to see if the list refers to changes, if there are changes in the changes to rewrite the corresponding DOM (without angular have to write this part of the code, if you have 100 variables, you have to write 100 such changes, and if there are any changes in the future, you still have to refactor yourself).


Some references about angular principle mechanism:

http:///archives/64167

/articles/fAfiMv

Two more notes here.

The watchlist will be rotated at least twice, why? Because the first rotation may trigger other variables in the watch list to change when rewriting the DOM, and then it will rotate again until the variables in the two consecutive rotations don't change anymore. So if you have two variable changes are interacting with each other, that is, A changes trigger B changes, B changes trigger A changes, this will cause a dead loop, angular seems to be in the training 5 times (or 10 times, I forget), if you still find that the value is not stabilized, it will be reported as an error (I've ever done it before, the interface suddenly jammed, the whole browser is jammed, and it was not easy to open the console to look at it, all). I was able to open the console and see that all the errors were reported by angular training, and angular's training directly jammed the whole browser).

2. another point, regarding efficiency, was raised that angular such undifferentiated rotations might affectperformancesBut angular's founder gave an explanation, people can see up to 200 elements on a page, there won't be so many elements binding data on a web page, if binding so many elements need to be updated in real time, it belongs to the web page design problem (quoted from *, can't find the specific url), so there is no need to worry about the efficiency of the training round, if there is really efficiency problem, it means the web page itself may have problems (I saw a post on Douban, one person used angular to measure 500 ngModel binding page, it was very laggy. If you really have efficiency problems, the web page itself may have problems (see a post on Douban, a person with angular measured 500 ngModel binding page, it is very stuck, so for unnecessary binding, it is best not to bind)

 

angular components

Controller

Controller is an important component of angular, basically angular will use controller. controller, as the name suggests, is used to control, is the MVC C, logic control. In angular, controller is a JavaScript constructor, this function has two roles, initialize scope, and add behavior.


Quote from:/guide/controller

Here a little simple explanation of the scope (later will say a little), scope is an object (object) can be understood as a bridge connecting the view and controller, the scope of the attributes of some of the value, there are some methods (behavior), in the html can be directly accessed, the following chart, ng-click inside the Those methods are all attributes of the scope, as well as the values displayed. After initialization in the scope, in the view (that is, in the html, angular official called template), you can access these values, you can also trigger these methods, which is the specific use of angular two-way data binding (very simple, no need to write a bunch of jquery).

Quote from:/guide/controller

So the controller's role is to initialize the scope and add methods to the scope, and angular has also given a number of ways to do this that are not recommended (see below), because there are basically better ways to do things this way

Quote from:/guide/controller

Tips:

1. angular in version 1.2 after a controlleras more syntax, this syntax allows for the controller to give an individual name (there is a feeling like sql inside the as), the following figure


If you do not use this syntax, you need to controller this function inside the Dependency Injection (Dependency Injection, will be introduced later, such as the example shown above, in the function of the parameter to write a $scope). If you use this syntax, you don't have to, the difference is that you don't have to use controller as syntax, html accesses the data by accessing the scope's attributes, so you need to write the data for the html to access into the scope's attributes, if you use controller as, the whole controller instance (the demo in the example) would be As an attribute of the scope, for example, if html wants to access the value of a data attribute, it should write the data for html to access into the attribute of the scope.

Controller as accesses the

The Controller accesses the

2. controller inheritance, each controller inheritance is actually scope inheritance, can be simply understood as JavaScript inheritance, you can see my other blog (if you have time to send it T^T), or angular official document said above. Here is if the child controller does not specify the data, it will use the parent class, if it is specified, it will use the child class, but note that if you change the value of the model, it is possible to change the value of the parent class (the following will also introduce this concept)

 

 

Service

Service can be understood as the MVC structure of the M layer, to deal with specific business logic, the ideal code is in the view triggered the controller function, and then the controller to call the model inside the specific processing, and then the model returns to the controller to change the scope of the data, the reaction in the view above. Service is this role, in angular, service has two characteristics

1. lazy loading (lazy loading): only when you need to use (that is, in other service, filter, directive or controller dependency injection will generate the service instance)

2. single pattern (singleton): service in angular is a single instance (singleton), only in the first injection to create instances, and then exist in the cache, and so on the need (that is, another dependency injection time), from the cache out. So the service's lifecycle will always have the instance as long as it is created, unless the app exits. Can not be destroyed (I have not found a way to manually destroy, in fact, in the Internet to find some examples of the need to destroy, in fact, can be used in other ways to do, do not necessarily have to destroy the service instance)

/questions/32781488/how-to-destroy-an-angular-factory-instance

 

PS: If you need to use the process of multiple instances of the look, you can slightly change their own, the service as a factory mode, return a variety of instances needed. You can refer to the following connection (the two examples are actually the same, just a little different in the way the service is written, in addition to the tips link inside the web page in the embed tab bar inside you can see the style)

/rbdmjLok/3/

/jeremylikness/rbdmjLok/

  • Register service

In the official developerguide given inside the main two ways, factory mode and provider mode, but in fact there is a service mode, so there are a total of three:

1.        factory:angular里面比较常用(used form a nominal expression)一种方式,注册一个function,this onefunctionWhen generating an instance it will be called on the,this one函数返回一个servicean actual example(You have to write it yourself.return(used form a nominal expression)),所以只要把自己需要(used form a nominal expression)serviceWrite it as aobj,在this oneobj里面定义要(used form a nominal expression)方法和值,and then finallyreturn一下this oneobjThat's it.,figure below

2.        service: service registration is much simpler, equivalent to the factory to do a layer of encapsulation. Just write the required methods and values inside the service on the line, no return, as follows

3.        providerProvider is the lowest level way to register service in angular, whether it is service or factory registration, in fact, the bottom is to use the provider this way. Inside the provider there is a $get attribute, this attribute is a function, this function is the factory inside the function we wrote, with the service kind of writing here is new a service that function to it (js inside the function can also be regarded as an object, so it is the same as directly) new an object to $get), angular is through dependency injection (will be introduced later), call this function to obtain an instance.

If a service only in the instantiation of it before knowing a configuration, such as reading the file or the network to return to some dynamic configuration, this can not be written in the code inside the dead, you need to pass parameters to the initialization of the service (somewhat similar to Java, C + + + inside the parameter constructor), then you need to configure the provider inside. So the provider is in the service before the initialization of the service to do some configuration of the component (so called provider it), in the provider to leave an interface (that is, to leave a function), and so on to get to the configuration of the need to call the provider's interface, you can set the parameters of the service. Note: here the provider just provides such a method, it can be understood as a tool, config is to call the provider of the East East. As for why not directly invoke the provider, but also add a config, I could not figure out at first, and then asked my boss, he thought it was just for good understanding, so that people look at it know that is the configuration. Later I also thought about it, it should also be for the convenience of unified configuration. If you directly call the provider to build, either write separately, or write a function in the configuration, angular probably should be in order to provide a unified and easy to understand the interface it (personal understanding). Specific examples are as follows (note: the name written inside the provider, when used in the name will be added to the name of a provider, such as the example written in the User, but the actual call to the provider is UserProvider)

 

In the use of the above three kinds of which way, the official document does not seem to give any too obvious advice, I think so, service is more inclined to be a service, factory tends to be a tool, the provider is the need to do some configuration of the service. The following blog is well-written, which also describes when to use which mode, attached are some references.

/tanweijie/blog/295067(The above graphs are quoted here)

/guide/services

/questions/15666048/angularjs-service-vs-provider-vs-factory?rq=1

 

scope

scope is the bridge connecting the controller and the view, angular official description: Scopeis the glue between application controller and the view (as can be seen in the above example)

  • scope external api:

scope provides three main external APIs (only two are mentioned in the developer guide in the official documentation)

Listen for changes to the model, and note that watch provides three types of api listener.

(1)(scope.$watch(watchExpression, listener)It only listens for the corresponding value or reference to change, and if it does, it triggers the registered callback function (i.e., the listener).

(2)(scope.$watchCollection(watchExpression, listener): listens for changes in the corresponding value or reference and in the collection (e.g., increase or decrease in the collection, but not in the value of the collection).

(3) (scope.$watch (watchExpression, listener, true)): listens for changes in the corresponding value or reference and in the collection and also for changes in the values inside, the following figure shows the difference more clearly

Publish the message of model change outside of angular context (PS: if change outside of angular context, angular won't update the interface, for example, use setTimeOut to update the model, because setTimeOut just put an event into the queue, it won't be executed immediately), when the timeout function is executed, if it is totally unrelated to angular, that is, it doesn't use some built-in commands, it won't trigger to enter into angular context. When the timeout function is executed, if it has nothing to do with angular, i.e. it doesn't use angular's built-in commands, it won't be triggered to enter the angular context, so the operation at this time is completely outside of the angular context, so even if the data of the model is updated, it won't be updated in the interface. So even if you update the model data, it won't be shown in the view, so you need to call apply by yourself to update it outside, you can refer to the blog below for specific examples. (Generally, in the command at the beginning of ng and angular comes with some service inside will automatically call apply, so we don't need to call it.)

This is not listed in angular's official documentation, but it can be called directly, which is not recommended. Calling apply will call digest, digest will rotate those watches (registered to listen to the list of those values), if found that the value has changed will call the watch to register that function to do some processing, can be understood as apply->digest->watch

Reference Self:http:///archives/64167

  •  Scope Type

scope is divided into two kinds, one is child scope, one is isolatescope, the former is in accordance with the inheritance relationship similar to the DOM structure, the latter is completely independent (generally used in the directive, because the directive is generally out of context, can be used independently, for example, to do a general list, when used only need to pass a list of values into it, this has nothing to do with the context, so it is generally independent, similar to the adapter in Android)

  • scope inheritance

Inheritance from the child scope is similar to JavaScript inheritance, which simply means that if a property is not present in the child scope, it will go to the parent scope to find it, one layer at a time.


If you want to assign a value at this time, it won't change to the attribute in the parentScope, for example, = 1, if there is no a specified in the childScope, then it is also 1, but if you assign = 2 at this time, then it is still 1. Why? Because that assignment statement is not a statement to change the value of JavaScript, it is to create an attribute value of a in the childScope equal to 2, so the parentScope will not be affected. 2, so the parentScop is not affected. But if the property is a model (that is, an object) is not the same, that access to the model when the reference (here and C++ is not the same, Java and JavaScript inside the class as a reference to pass, C + + + is through the copy constructor copy a copy, unless you modify the copy constructor, the default is to pass the value of), for example: = 1, if the value of a property for the childScope is not a change in value statement for JavaScript, it is to create a property value for the childScope is equal to 2, so the parent parentScop is not affected. ), for example: = 1, if the childScope is not specified, then it is also 1, then the assignment = 2, then the parent is also 2. Why, because it is access to the properties of the parentScope (if the childScope is not specified, note that this premise), as a model (object), so the access is the address (reference). reference), then =2 is rewriting the value of this address, so the parentScope will also be changed. Of course, if you put =newA first, so the childScope points to a value that is not the parentScope, and then change the value of a, it will not affect the parentScope. It is recommended to change the value of a in theconsoleTry it inside (function is actually class in JavaScript, and my other blog also describes the inheritance relationship between JavaScript and angular)

Reference Self:

/angular//wiki/Understanding-Scopes

/guide/scope

  • Tracking scope

This is angular official give how to debug the scope in the view, that is to say, look at the scope of the current value of some

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 this global variable, so that you can in the console from this global variable inside the scope want to track the value of the value. But note: if the global variable is only for debugging, do not use it in the code.utilizationThis global variable, i.e. don't read it, because it exists only for debugging purposes, is something that can be removed at any time, and if there is code logic that depends on the value of this global variable, it will result in an error when it is removed. So don't let the code depend on a variable that will be removed at any time.

  • Scope event distribution

This in the project we basically did not use, but angular provides this mechanism, emit and broadcast (do Android students should have a better feel for this word, but in fact this is similar to Android inside the event delivery mechanism event dispatch, such as touchEvent and clickEvent). This kind of, but angular this does not seem to exist consumption, because the project does not use this, so I have not carefully examined, please tell the gods)

emit:

Release the event, both the current scope and the parent scope can receive this event, and if there is a callback registered for this scope inside the corresponding scope, this callback function will be called.

Broadcast:

Publish the event, both current scope and sub-scope will receive the event, and if there is a callback registered for this scope inside the corresponding scope, the callback function will be called.

Specific examples can be found in

/guide/scopeScope Events Propagation section



DependencyInjection

Dependency injection is a thing that is mentioned in many programming languages and frameworks. In fact, it is very good to understand, first of all, what is a dependency, A module (such as classes, methods), need to use the B module in the things, this time it is said that the A on the B has a dependency, for example, there is an add method inside the A class, inside the B class need to use this add method, that is, the B has a dependency on A. This time you need to inject (in fact, injection can also be understood as the initialization of this kind of meaning), in Java, you may need to new a A, in angular inside, directly with the function parameter form to write, but to first define this dependency elsewhere, that is, to define a service (such as the service mentioned above that part), and then pass this service as a function parameter. This is equivalent to new such an object. You can refer to the example in the service section above or the official angular example.

There are three ways to write dependency injection in angular:

ArrayAnnotation:

Write it in single quotes inside the center brackets and inside the function's arguments, and be careful to order it consistently

 

2.$inject PropertyAnnotation

Write it with $inject, and also be careful to have a consistent order of arguments

Writing only inside the function's parameters is the simplest way to write, but it's also not recommended by angular. Because this kind of writing will cause problems in code obfuscation, of course, there is a tool to solve this problem, not mentioned here, see angular official documentation for more details/guide/di

In addition, angular also provides a harsh mode (Android actually has a harsh mode, but different from angular, Android students do not get confused), does not allow Implicit Annotation, once you use Implicit Annotation will report an error, this is not introduced. See angular official document ditto. In addition, there are three ways to solve the dependency problem (see below), but angular thinks that the first two ways are not good, because the first two have to code their own, which is troublesome, especially in theunit testThe third way is to use the $injector to create and track dependencies, which reduces the burden on the developer. For more details, please refer to angular's official documentation, so I won't mention it here.

 

template

The template inside angular is actually html, in angular, you can use the following four ways to control the display of the template (html) (as shown in the figure), are relatively simple, look at the example will know, here will not be mentioned. angular suggests that if it is a simple app, you can write all the html in the same html file, and then use directive to control these (generally is), if a little more complex app, you can put different views (which is html) in the same page, but define the respective view in different html files. Then use directive to control (generally), if more complex app, you can put different views (that is, html) in the same page, but define the respective views in different html files, and then loaded in the page by reference (our project is done in this way, it can be regarded as one, but not the same as the other. In fact, it can be considered as one, but many views in it are from other html files)


Reference Self:

/guide/templates


Afterword: I would like to carefully study angular official documents and then send, but then realized that I have written more than six thousand words, put in an inside hair is not very good, just that the introduction of angular some of the basic components, is considered the foundation of the chapter it. Secondly, it just happened to catch up with the company's business restructuring, now also need to take over the work of other business lines, the back may not have much time to write how much js, so the first issued, but also on the past period of time to write angular a small summary, I hope to have time to write a sequel to this blog it.


Higher because of those who came before us

1 .:/angularjs/(Beginners can take a look at this to get a quick grasp of some of the basics to use)

2. angular official document developer guide:/guide/concepts(You can look backward from the module concepts, most of this article is based on the angular developer guide, mainly from the same site, the article has been indicated, in this case will not list the references of each module)

How it works:http:///archives/64167

How it works:/articles/fAfiMv

About how to destroy service: /questions/32781488/how-to-destroy-an-angular-factory-instance (the last respondent suggests not to destroy, in fact, you can use other ways to realize the business logic, the main purpose here is to illustrate that in fact, many times you do not have to destroy the service, you can use other ways to do)

6. polymorphic service writing:/rbdmjLok/3/ (Example of a counting service that counts separately in two places, with one service used independently in multiple places)

Difference between the three constructor methods:/tanweijie/blog/295067

Difference between the three constructor methods:/questions/15666048/angularjs-service-vs-provider-vs-factory?rq=1

and inheritance between angular:/angular//wiki/Understanding-Scopes(This article is quite good and worth reading)