Angularjs Concepts Detailed and sample code _ANGULARJS

Source: Internet
Author: User
Tags exception handling html tags tag name


Original address: Http://code.angularjs.org/1.0.2/docs/guide/concepts



Go on..



First, the overall



This article is primarily an overview of the angular component (components) and explains how they work. The list is as follows:


    1. Statup-Still the Hello world ... Change to Hello kitty!
    2. Runtime-Introduction to Angular's runtime
    3. Scope-view and Contorller of the Bond (God horse glue ... Gel
    4. Controller-app behavior (application behavior)
    5. Model-app's data
    6. View-What the user sees
    7. Syntax extensions for directives-html
    8. Filters-Format data according to the user's local format
    9. Injector-Loading our app (dependency management and the like)
    10. Module-Configure Injector
    11. $-Angular namespace (namespace)


Second, start (startup)



The following describes how angular is started (refer to the chart with the following example):



1. The browser loads HTML to convert HTML tags into DOM objects;



2. Browser loading angular.js script;



3. Angular waits for the domcontentloaded event;



4. Angular seeks ng-app this directive to specify the boundary range of the application;



5. If Ng-app has a specified module (perhaps ng-app= "Someapp"), it will be used as a configuration $injector;



6. $injector for the creation of $compile Services (service) and $rootscope;



7. The $compile service is used as a "compilation" (a bit like traversing, then doing something mysterious) DOM and connecting it to the corresponding $rootscope.



8. Ng-init This directive creates the name attribute in the corresponding scope and assigns a "Kitty" value to it;



9. Inserts the value of ' {{name}} ' into the expression, which eventually displays "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>


Because of discussing something with others tonight, the progress is slow ... Again the sentence ... It's already late at night ... Angular, see you after the ad!



==============================================



Advertising finished ... Go on



Third, Runtime






This chart and the following example, describes how angular through the browser event-loop (all the time processing functions, and the functions that timer executes, will be in a queue structure, using an infinite loop, constantly fetching functions from the queue to execute, This is event-loop. From Http://wiki.nodejs.tw/nodejs_from_scratch/javascript-yunodejs/2-1-event-loop) to interact.



1. Browser Event-loop waiting for the event to arrive. Events come from user interaction (DOM events), Timer events (settimeout), network events (server-side responses, XHR, and so on);



2. The event callback function begins execution. This goes into the JavaScript context. This callback function can modify the DOM structure.



3. When the callback function completes, the browser exits the JavaScript context, redrawing the view based on the DOM changes.



Angular modifies a generic JavaScript stream (flow) by creating its own event-handling loop (the events processing loop). This divides JavaScript into traditional and angular execution contexts (execution context). As long as the operation in the angular execution context, all have angular data-binding, exception handling (exception handling), attribute monitoring (property watching) capabilities. We can use $apply () in JavaScript to enter the angular execution context. Remember, however, that in most (angular) places (such as controllers, services), the directive that handles events will call $apply for you. Manually invoke a $apply scenario, usually when you implement a custom event handler, or handle a callback for a Third-party library.



1. Enter angular execution context by calling scope. $apply (STIMULUSFN). STIMULUSFN is the function we want to execute in the angular execution context (with scope as a parameter) or a angular valid expression.



2. Angular performs STIMULUSFN, which usually changes the state of the application (application).



3. Angular enters $digest loop. This loop consists of a smaller loop that handles the $evalasync queue and handles $watch list two. $digest Loop holds the iteration before model stability, that is, the $evalasync queue is empty, and the $watch list does not detect any changes.



4. $evalAsync queue is used as a schedule that must jump out of the current stack frame (the stack frame refers to the area (or space) that is assigned to the currently running function in the stack. The arguments passed in, the return address (when this function ends, you must jump to the return address.) That is, the breakpoint at the keynote function, and the internal storage unit used by the function (that is, the local variables stored on the stack by the function) are in the stack frame. http://book.51cto.com/art/200804/70915.htm c.1.1 stack frame), but before the browser view is drawn. This is usually done by using settimeout (0). But settimeout (0) This method can cause slow, or when the browser draws a view after each event has been processed, the view flashes (does angular solve the problem?). How to solve? )。



5. $watch list is a collection of expressions that are likely to be modified in the most recent iteration. if (model) has changed, then the $watch function is invoked to achieve the target of a specific DOM reset.



6. Once the angular $digest loop completes (as mentioned in the previous 3), after leaving the context of angular and JavaScript, the browser will immediately redraw the DOM to respond to changes.



The following explains the example "Hello Kitty" (-_-!) is how to implement data binding (data-binding) effects when a user enters text in a text box.



 1. Compile phase (compilation phase):



A) Ng-model and input directive KeyDown event listeners in the <input> version.



b) {{name}} placeholder (interpolation, not knowing how to translate) (expression) sets a $watch to respond when name changes.



 2. Implementation phase (Runtime Phase):



(a) press the "X" button in the Inut control to allow the browser to trigger a KeyDown event;



b) input directive captures changes to the value of the text box and then calls $apply ("name = ' X ';") to update the applied model in the angular execution context.



c) Angluar will "name = ' X ';" Apply in model. (model changes)



d) $digest Loop start



e) $watch list detects that the value of name is changed, then resolves the {{name}} expression again, and then updates the DOM.



f) Angulart exit (angular) execution context, and then exit KeyDown event and JavaScript execution context in turn;



G The browser redraw the view to update 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" class="ng-cloak"/>
  <p>Hello {{name}}!</p>
<script src="../angular-1.0.1.js" type="text/javascript"></script>
</body>
</html>


Iv. Scope



Scope is responsible for detecting changes in the model and as the execution context of the expression (execution contexts). Scope is nested within a hierarchy similar to that of a DOM structure (it is understood before that the partition may be related to controller). (For more information see individual directive documentation, see which directive will create a new scope)



The following example shows that the value of the expression "name" is determined by the scope it relies on (the owning), and also includes the way in which the value is searched (similar to the scope chain of JS, no one is looking for 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 class="ng-cloak" ng-controller="ControllerA">
  Hello {{name}}!;
</div>
<div class="ng-cloak" ng-controller="ControllerB">
  Hello {{name}}!;
  <div class="ng-cloak" ng-controller="ControllerC">
    Hello {{name}}!;
    <div class="ng-cloak" 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 = 'Lcllao';
  }

  function ControllerC($scope) {
    $scope.name = 'Jeffrey';
  }

  function ControllerD($scope) {

  }
</script>
</body>
</html>


Five, 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 class="ng-cloak" 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 model, and through the callback function, push its (model) into the view. View is the current scope to template (HTML) mapping (a bit reluctantly ...) )。 Scope is the link that directs model to view and sends an event to controller.



Controller and view separation are important because:



1.Controller is written in JavaScript. JavaScript is imperative (imperative). Command (imperative) is a good way to describe the behavior of an application. Controller should not contain any display information (the logic) (DOM reference or HTML fragment)



The 2.View template is written in HTML. HTML is declarative. Declarative (HTML) is a good way to describe the UI. View should not contain any behavior.



3. Since controller does not know which view it needs to correspond to, a controller can (indirectly) use multiple view. This is for re-skinning (change skin?) , other device-specific views (such as mobile phones and desktops) and the testability of the code are important.



Six, Model






Model, can be understood as a data object. It is used as a combination with templates to produce views. In order to write model to a view, the model must be referenced by scope. Unlike many other frameworks, angular does not have any restrictions or requirements for model. You do not need to add class, nor do you need a special privileged method to access or change model. The data type of model, can be the original type (string, number ...). Can be a key-value object ({A:1,b:2}), or a function (functions () {...} )。 Briefly, angular's model only needs to be an ordinary JavaScript object.



Seven, View



View is what the user can see. View was born in a template. It is combined with model and eventually renders as a browser dom. Angular takes a different approach to rendering 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 break the syntax of HTML, which means you can't edit the code through a generic HTML editor. )。 Template string incoming template engine, merged with data. Finally, the HTML string is generated. These strings are typically written to the DOM in the form of. 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 stencil is consistent with the granularity of the DOM update. The key to this is the template system processing strings.



The difference between the angular:angular template is that it is DOM based rather than string based. Templates still need to write some strings in HTML, but still HTML (not by embedding templates inside). The browser converts HTML to DOM, and the DOM becomes input to the compiler (angular's template engine). Compiler find directives, and then set watches in model. The result is a constantly updated view, do not need to be spliced model and template. Model becomes the only data source for view (single source of Truth).



Eight, directives



Directive is a behavior (for example, "Hide-and-seek") or DOM conversion (a custom tag, which contains a set of DOM), which can be triggered by placing its name in the attribute, tag name, and class name. Directive allows you to extend HTML tags in a declarative way.



In the following example, there are some questions. is $render how to trigger @_@


<!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 class="ng-cloak">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>


Nine, Filters



Filters plays a role in Data transformation (formatting). Usually they are geographically related, and different regions may have different output formats.  They are following the spirit of the UNIX filter 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 format: 1233211234567-> {{1233211234567 | number}} <br/>
   Array filtering, then output in 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>


X. Modules and the Injector






Injector is a service locator. Each angular application will have a separate injector. Injector provides a way to find an object instance by name. Injector keeps all object instances in the internal cache, so when you call the same name repeatedly, the same object instance is returned. If the object does not exist, it requests the instance factory (instance factory) to create a new instance.



Module is a method for configuring injector instance factories, known as "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 ');//true


But Injector's real cow x is where it can be used to invoke methods and "instantiate" type. This wonderful feature is to allow method and types to request the resources they rely on rather than looking for them.


 You are write functions such as this one.
  function dosomething (ServiceA, SERVICEB) {
  //do something here.
  }
   
  Angular provides the injector for your application
  var $injector = ...;
  //The Old-school way of getting dependencies.
  var servicea = $injector. Get (' ServiceA ');
  var serviceb = $injector. Get (' ServiceB ');
   
  Now call the function
  dosomething (ServiceA, SERVICEB);
   
Above is the traditional old method ~ below is angular said his own cow x method

  ///////////////////////////////////////////////
  //The cool way of getting Dependencies.
  The $injector would supply the arguments to the function automatically
  $injector. Invoke (DoSomething); W The framework calls your functions



Note that the only thing we need to write is our function, which lists the resources that the method relies on in the arguments of the function! When angular invokes a function, he uses the "call" method to automatically populate the function agruments.



Note how the dependencies are listed in the constructor in the following example. When Ng-controller instantiates controller, the dependent resources are automatically provided. There is no need to create, find, and create injector references to load dependent 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" class = "ng-cloak">
   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 dependent myClock is automatically inserted here! !
    * @constructor
    * /
   function ClockCtrl ($ scope, myClock) {
     $ scope.time = myClock;
   }
</ script>
</ body>
</ html> 


Xi. Angular Namespace



To prevent name collisions, angular adds a prefix of $ to the name of object. Do not use the $ prefix in your code to avoid conflicts. (-_-!! )



The above is about ANGULARJS concepts data collation, follow-up continue to add related articles, thank you for your support of this site!


Related Article

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.