What you think when you first know the angular frame _angularjs

Source: Internet
Author: User

Because the actual development need in the work, only then starts to contact the angular frame. From the original Bishi, by various problems, the concept of torture and destruction, to now have a certain understanding, feel the need to make a simple summary of their own understanding. Not in place also hope to forgive.

1. Bidirectional data binding
the current industry is rife with various mv** frameworks, and the relevant frameworks are emerging, and angular is one of them (MVVM). mv** Framework in fact, the most important problem is to separate the view layer and model, reduce the coupling of the code, so that the data and performance of the separation, MVC, MVP, MVVM have the same goal, and the difference between them is how to link the model layer and view.

How to flow the data in model and view layer is the key of the problem, and angular realizes the two-way binding of data through Dirty-check. The so-called two-way binding, that is, view changes can be reflected to the model layer, and model data changes can be reflected in the view. So how does angular do two-way binding? Why become Dirty-check? Or the front end of a primitive problem set out:

Html:

 <input type= "button" value= "Increase 1" id= "j-increase"/> <span "id="
 ></span>

Js:

 <script>
 var binddate = {
  count:1,
  appy:function () {
   document.queryselector (' #J-count '). InnerHTML = This.count
  },
  increase:function () {
   var _this = this;
   Document.queryselector (' #J-increase '). AddEventListener (' click ', Function () {
    _this.count++;
    Appy ();
   }, True);
  },
  initialize:function () {
    //Initialize
   this.appy ();
   this.increase ();
   }
  ;
  Binddate.initialize ();
 </script>

In the example above, there are two processes:

View layer Impact model layer: Click button on the page, resulting in an increase in the number of data count 1
model Layer Reaction view layer: After count has changed, the Apply function is used to reflect on the view layer
This is the previous use of jquery, Yui, such as the implementation of class library data processing, which exists in the problem is obvious:

    • Involves a large number of DOM operations;
    • The process is tedious;
    • Code coupling is too high to write unit tests.

Let's look at how the angular is processed:

First step. Add Watcher: is when the data changes, what needs to detect which objects, need to register the advanced line

The source code in the angular is streamlined 
 $watch: function (watchexp, Listener, objectequality) {
  var scope = This,
   array = scope . $ $watchers,
  watcher = {
    Fn:listener,
    last:initwatchval,
   get:get,
   exp:watchexp,
    eq:!! Objectequality
  };
  if (!array) {
   array = scope.$ $watchers = [];
 }
  Array.unshift (watcher);
 }

Step two. Dirty-check: That is, when the data in a scope scope changes, you need to traverse the $ $watchers of the detection register = [...]

 $digest: Function () {while
 (length--) {
   watch = watchers[length];
  Watch.fn (value, lastvalue, scope);
 }
 

This enables two-way binding of data, does the implementation of the above resemble a custom event? You can see the use of the observer design pattern or (publisher-subscriber).

2. Dependency Injection
Students who have used the spring framework know that IOC and AOP are two of the most important concepts in spring, and that the IOC can inject dependency (DI), which obviously angular with very strong back-end colors.

Again, the first thing to look at is how to resolve objects that are dependent on each other without using di:

 function car () {
 ...
}
 Car.prototype = {
 run:function () {...}}
}
 
function Benz () {
 var cat = new Car ();
 }
Benz.prototype = {
  ...
}


In the example above, class Benz relies on the class car to resolve this dependency directly through internal new. The disadvantage of this is very obvious, code coupling to become high, not conducive to maintenance. The backend framework has long been aware of this problem, and spring early on, by registering dependencies between objects in an XML file, and later by Anotation to solve the di problem more easily, the Cos side can look at the backend code.

The JS language itself is not a annotation (annotation) mechanism, that angular is how to achieve it?

1. Analog annotation

 The mock
 function annotate (FN, STRICTDI, name) of the annotation {
 var $inject;
 if (!) ( $inject = fn. $inject)) {
  $inject = [];
  $inject. push (name);
 else if (IsArray (FN)) {
  $inject = fn.slice (0, last);
 }
  return $inject;
 }
 createinjector.$ $annotate = annotate;

2. Injection object creation

 function Createinjector (modulestoload, STRICTDI) {
  //Create object
  var Providercache = {$provide in singleton mode
    : {
      Provider:supportobject (provider),
      Factory:supportobject (Factory),
      service:supportobject (service)
      , Value:supportobject (value),
      constant:supportobject (constant),
     decorator:decorator
   }
   },
  Instancecache = {},
  Instanceinjector = (instancecache. $injector =
  Createinternalinjector (Instancecache, function (ServiceName, caller) {
  var Provider = Providerinjector.get (ServiceName + providersuffix, caller);
     Return Instanceinjector.invoke (provider. $get, provider, undefined, serviceName);
    });
 return instanceinjector;
 }


3. Get Injected Object

function Invoke (FN, self, locals, serviceName) {
 var args = [],
  $inject = Annotate (FN, STRICTDI, serviceName); 
   
    for (...) {
  key = $inject [i];
   Replace with dependent objects
   Args.push (
   locals && locals.hasownproperty (key)
     Locals[key]
    : GetService (Key, ServiceName)
   );
 }
  if (IsArray (FN)) {
  fn = fn[length];
  }   
  Return fn.apply (self, args);



   

Here, whether is to see a lot of back-end framework design ideas, no anotation on the simulation of a, no wonder PPK to say angular is "a front-end framework by Non-front-enders for Non-front-enders "

3.controller Communication
In the actual development, the application system will be very large, an application app can not exist only one controller, then there is the possibility of communication between different controller, how to solve this common problem, there are two main methods:

1. Event mechanism: Register the event on the $rootscope, the problem is to register too large an event on the $rootscope, causing some follow-up problems

 Controller1
app.controller (' Controller1 ', function ($rootScope) {
 $rootScope. $on (' EventType ', function ( ARG) {
    ...
  }

}) Controller2
app.controller (' Controller2 ', function ($rootScope) {
   $rootScope. $emit (' EventType ', arg);
 or
  $rootScope. $broadcast (' EventType ', arg);
 })

2. Through service: make full use of angular di characteristics, using service is a single example of the characteristics of different controller play a role in the bridge between

Registration Service
app.service (' message ', function () {return
 {
  count:void (0);
 }
 })
 Controller1, modify the service's count value
app.controller (' Controller1 ', function ($scope, message) {
  $scope. Count = 1 ;
 Message.count = $scope. Count;
});
 Controller2, gets the service's count value
app.controller (' Controller2 ', function ($scope, message) {
$scope. num = Message.count;
 });

The characteristics of 4.service

1. Single case (singleton): angular inside only service can carry on di such as, controller, Directive None of these functions, service is literally to provide some basic services, Not related to the specific business, while controller, Directive is closely associated with the specific business, so you need to ensure the uniqueness of the service.

2. Lazy NEW:angular will first generate service provider, but does not immediately generate the corresponding service, only when these services are required to be instantiated operation.

3. Provider) Classification: provider (), factory, service, value, constant, where provider is the lowest implementation, other methods are based on the syntactic sugar (sugar), It is to be noted that these services are ultimately added to the $get method, as the specific service is generated by executing the $get method.

5. Implementation of Directive
Directive's compilation (compiler) consists of two phases: compile, link. Simply speaking, the compile phase mainly deals with template DOM, which does not involve the scope problem, that is, no data rendering, for example, the ngrepeate instruction is template modified by compile, and the link function is returned after the execution of compile , cover the link function defined later, and link is mainly for data rendering, divided into Pre-Link and post-link two links, these two links to parse the order is the opposite, Post-link is the first analysis of the internal, and then the external, This parsing of directive is safe because the directive can also include directive, and link is the processing of the real DOM, which involves performance issues with DOM operations.

The content of this article is not very popular, then there will be a corresponding supplement, I hope you can also study the angular framework.

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.