Understanding ANGULARJS Instructions _angularjs

Source: Internet
Author: User
Tags anonymous

For instructions, it can be simply understood as a function that runs on a particular DOM element, and instructions can extend the functionality of that element.

Let's take a look at a complete parameter example to describe the function and usage of each parameter in detail:

Angular.module (' myApp ', []) 
. Directive (' mydirective ', function () {return 
  { 
    restrict:string, 
    Priority:number, 
    Terminal:boolean, 
    template:string or template function: 
  function (TElement, tattrs) { ...}, 
  templateurl:string, 
  Replace:boolean or String, 
  Scope:boolean or Object, 
  Transclude:boolean , 
  controller:string or 
  function (scope, element, Attrs, transclude, Otherinjectables) {...}, 
  Controlleras:string, 
  require:string, 
  link:function (scope, ielement, Iattrs) {...}, 
  compile:// Returns an object or Join function, as follows:
  function (TElement, tattrs, transclude) {return 
    { 
      pre:function (scope, ielement, Iattrs, controller) {...}, 
      post:function (scope, ielement, Iattrs, controller) {...}} 
    return function Postlink (...) { ... } 
    } 
  }; 
 });

1, restrict[string]

Restrict is an optional parameter. Used to specify in what form the directive is declared in the DOM. The default value is a, which is declared in the form of a property.
The optional values are as follows:
E (Element)

<my-directive></my-directive>
A (properties, default values)

<div my-directive= "expression" ></div>
C (class name)

<div class= "my-directive:expression;" ></div>
M (note)

<--directive:my-directive expression-->
Generally, with browser compatibility in mind, it is strongly recommended that you use the default property to declare it as a property. The last way is to recommend that you do not use the force index when you don't want it.

Code:

 Angular.module (' app ', [])
  . Directive (' mydirective ', function () {return
      { 
        restrict: ' E ', 
        Template: ' <a href= ' http://www.baidu.com ' > Baidu </a> ' 
      }
Htmlcode:
 <my-directive></my-directive>

Effect:

2, Priority[int]

Most directives ignore this parameter, using the default value of 0, but some scenarios setting high priority is very important or even necessary. For example, Ngrepeat sets this argument to 1000, which guarantees that it will always be invoked on the same element before other directives.

3, Terminal[bool]

This parameter is used to stop the instruction from running the current element with a lower priority than this instruction. However, instructions that are the same as the current instruction priority are executed.
For example, the Ngif priority is slightly higher than the ngview (they manipulate the actual terminal parameters) and can be performed correctly if the Ngif expression value is True,ngview, but if the value of the ngif expression is false, The Ngview is not executed because it has a lower priority.

4, template[string or function]

The template parameter is optional and must be set to one of the following two forms:

    • A section of HTML text;
    • A function that accepts two parameters, the arguments telement and tattrs, and returns a string representing the template. The T represents template in TElement and Tattrs, which is relative to instance.

First demonstrate the second usage:

Angular.module (' app ', [])
  . Directive (' mydirective ', function () {return
      { 
        restrict: ' EAC ', 
        template : function (Elem, attr) {return
          "<a href= '" + attr.value + "' >" + attr.text + ' </a>;}}}
  )

Htmlcode: (The effect is ditto, do not do demo)

<my-directive value= "http://www.baidu.com" text= "Baidu" ></my-directive>
    <div
       my-directive Value= "http://www.baidu.com"
       text= "Baidu" ></div>

5, templateurl[string or function]

Templateurl is an optional parameter and can be of the following types:

    • A string representing the path of an external HTML file;
    • A function that accepts two parameters, parameters telement and Tattrs, and returns a string of external HTML file paths.

Either way, the template URL will pass through the security layer built into Ng, especially $gettrustedresourceurl, which protects the template from being loaded by untrusted sources. By default, an HTML template file is requested in the background by Ajax when the command is invoked. Loading a large number of templates will severely slow down the speed of a client application. To avoid delays, you can cache HTML templates before deploying the application.

Code:

 Angular.module (' app ', [])
  . Directive (' mydirective ', function () {return
      { 
        restrict: ' AEC ' 
        , Templateurl:function (Elem, attr) {return
          Attr.value + ". html";//Of course, here we can specify the path directly, while in the template can include the expression
        }
    };
  

6, Replace[bool]

Replace is an optional parameter, and if this argument is set, the value must be true because the default value is False. The default value means that the template is inserted as a child element inside the element that calls this directive.
For example, the above example defaults, the resulting HTML code is as follows:

<my-directive value= "http://www.baidu.com" text= "Baidu" ><a href= "http://www.baidu.com" > Baidu </a></ My-directive>

If you set Replace=true

<a href= "http://www.baidu.com" value= "http://www.baidu.com" text= "Baidu" > Baidu </a>

As far as I can see, this effect only shows the actual effect if the restrict= "E" is set.

After introducing the basic instruction parameters, it is necessary to involve more important scope parameters ...

7. Scope parameter [bool or object]

The scope parameter is optional and can be set to TRUE or an object. The default value is False.

If there are multiple directives on an element that use the quarantine scope, only one of them can take effect. Only the root element in the directive template can get a new scope. Therefore, scope defaults to True for these objects. The purpose of the built-in instruction Ng-controller is to inherit from the parent scope and create a new child scope. It creates a new child scope that inherits from the parent scope. The inheritance here is not to repeat, and object-oriented inheritance is basically always.

Let's start by analyzing a piece of code:

 <div ng-app= "App" ng-init= "Name= ' grandfather '" >
      <div ng-init= "name= ' father '" >
        first generation: {{name}}
        <div ng-init= "Name= ' son" "ng-controller=" Somecontroller ">
          second generation: {{name}} <div ng-init= ' name=
          ' grandson '" >
            Third generation: {{name}}
          </div>
        </div>
      </div>
    </div> 

We found that the first generation, we initialized name as father, but the second and third generations are actually a scope, then their name is actually an object, so the effect is as follows:

First generation: Father
Second generation: grandson
Third generation: grandson
We're modifying the code to isolate the third generation and look at the effect:

<div ng-app= "App" ng-init= "Name= ' grandfather '" >
      <div ng-init= "name= ' father '" >
        first generation: {{name}}
        <div ng-init= "Name= ' son" ng-controller= "Somecontroller" >
          second generation: {{name}} <div ng-init= ' name=
          ' grandson ' Ng-controller= "Secondcontroller" >
            third generation: {{name}}
          </div>
        </div>
      </div>
    </div>

Jscode:

 Angular.module (' app ', [])
    . Controller (' Somecontroller ', function ($scope) {
      
    })
    . Controller (' Secondcontroller ', function ($scope) {
    
  }) 

The effect is as follows:

First generation: Father
Second generation: Son
Third generation: grandson
Change the code to see the inheritance:

    <div ng-app= "App" ng-init= "Name= ' grandfather's Kiss '" >
      <div>
        First generation: {{name}}
        <div ng-controller= " Somecontroller ">
          second generation: {{name}}
          <div ng-controller=" Secondcontroller ">
            third generation: {{name}}
          < /div>
        </div>
      </div>
    </div> 

The effect is as follows:

First generation: Grandfather's Kiss
Second generation: Grandfather's Kiss
Third generation: Grandfather's Kiss

If you want to create a directive that inherits the scope from an external prototype, set the Scope property to True, which is simply inheritable isolation, that is, the parent scope cannot be affected in reverse.

Let's look at an example:

  Angular.module (' myApp ', [])
    . Controller (' Maincontroller ', function ($scope) {
    })
    . Directive (' Mydirective ', function () {return
      {
        restrict: ' A ',
        scope:false,//switch to {},true test
        priority:100,
        Template: ' <div> internal: {{myproperty}}<input ng-model= ' myproperty '/></div> '
      };
    

HTML code:

 <div ng-controller= ' maincontroller ' ng-init= ' myproperty= ' Hello world! ' " >
    external: {{MyProperty}}
    <input ng-model= "MyProperty"/> <div my-directive></div>
  </div>

When we change the value of scope, we will find

False: inherited but not isolated

True: Inherit and isolate

{}: Isolated and not inherited

8, Transclude

Transclude is an optional parameter. The default value is False. Embedding is typically used to create reusable components, typically a modal dialog box or navigation bar. We can pass the entire template, including the instructions, through embedding all into one instruction. The inside of an instruction can access the scope of the external instruction, and the template can also access external scope objects. In order to pass the scope in, the value of the scope parameter must be set to the isolation scope by {} or True. If the scope parameter is not set, the scope within the directive will be set to the scope of the incoming template.

Use Transclude:true only if you want to create an instruction that can contain arbitrary content.

Let's take a look at two examples-navigation bar:

<div side-box title= "Tagcloud" >
    <div class= "Tagcloud" >
      <a href= "" >Graphics</a>
      <a href= "" >ng</a>
      <a href= "" >D3</a>
      <a href= "" >Front-end</a>
      <a href= "" >Startup</a>
    </div>
  </div>

Jscode:

 Angular.module (' myApp ', []) 
 . Directive (' Sidebox ', function () {return 
   { 
     restrict: ' EA ', 
     scope: { 
       Title: ' @ ' 
     }, 
     transclude:true, 
     Template: ' <div class= sidebox ' ><div ' content ' class= Class= "header" > ' +
       ' {{title}} 
 

This code tells the NG compiler to place what it gets from the DOM element where it finds the ng-transclude instruction.

Here's another example of an official website:

Angular.module (' Docsisofnbindexample ', [])
 . Controller (' controller ', [' $scope ', ' $timeout ', function ($scope, $ Timeout) {
  $scope. Name = ' Tobias ';
  $scope. Hidedialog = function () {
   $scope. Dialogishidden = true;
   $timeout (function () {
    $scope. Dialogishidden = false;};
 directive (' Mydialog ', function () {return
  {
   restrict: ' E ',
   transclude:true,
   scope: {
    ' Close ': ' &onclose '
   },
   templateurl: ' my-dialog-close.html '
  };
 

My-dialog-close.html

<div class= "alert" >
 <a href class= "close" ng-click= "Close ()" >x</a>
 <div Ng-transclude></div>
</div>

Index.html

<div ng-controller= "Controller" >
 <my-dialog ng-hide= "Dialogishidden" on-close= "Hidedialog ()" >
  Check out the contents, {{name}}!
 </my-dialog>
</div>

If the instruction uses the transclude parameter, then the controller will not be able to monitor the data model changes properly. It is recommended that you use the $watch service in link functions.

9, controller[string or function]

The controller parameter can be a string or a function. When set to a string, the constructor of the controller registered in the application is looked up with the value of the string as the name.

Angular.module (' myApp ', []) 
. Directive (' mydirective ', function () { 
restrict: ' A ', 
controller: ' Somecontroller ' 
}) 

An inline controller can be defined within an instruction through an anonymous constructor

Angular.module (' myApp ', []) 
. Directive (' mydirective ', function () { 
restrict: ' A ', 
Controller: 
function ($scope, $element, $attrs, $transclude) { 
//Controller logic is placed here
} 
}); 

We can inject any injected NG service into the controller, we can use it in the instruction. There are also special services in the controller that can be injected into the command. These services are:

1. $scope

The current scope associated with the directive element.
2. $element
The element that corresponds to the current instruction.
3. $attrs
An object that consists of the properties of the current element.

<div id= "Adiv" class= "box" ></div>
has the following property objects:
{ 
ID: "Adiv", 
class: "Box" 
} 

4. $transclude
the embedded link function is bound to the corresponding embedded scope. Transclude link functions are functions that are actually executed to clone elements and manipulate the DOM.

 Angular.module (' myApp ', [])
 . Directive (' MyLink ', function () {return
   {
     restrict: ' EA ',
     Transclude:true,
     Controller:
     function ($scope, $element, $attrs, $transclude) {
       $transclude (function (clone) {       
         var a = angular.element (' <a> ');
         A.attr (' href ', $attrs. value);
         A.text (Clone.text ());
         $element. Append (a);
       });};
 };

Html

<my-link value= "http://www.baidu.com" > Baidu </my-link>
<div my-link value= "http://www.google.com" > Google </div>

Using Transcludefn only in the compile parameter is a recommended practice. The link function can isolate instructions from each other, while controller defines reusable behavior. If we want to expose the APIs of the current instruction to other directives, you can use the controller parameter, otherwise you can use link to construct the functionality (that is, internal functionality) of the current instruction element. If we use scope. $watch () or want to interact with DOM elements in real time, using links would be a better choice. With embedding, scopes in the controller may reflect a different scope than we expected, in which case $scope object cannot be guaranteed to be updated normally. When you want to interact with the scope on the current screen, you can use the scope parameter passed in to the link function.

10, Controlleras[string]

The Controlleras parameter is used to set the controller alias so that the controller can be referenced in the view without even having to inject $scope.

<div ng-controller= "Maincontroller as main" >
    <input type= "text" ng-model= "Main.name"/>
    <span >{{Main.name}}</span>
  

Jscode:

 Angular.module (' myApp ', [])
  . Controller (' Maincontroller ', function () {
    this.name = "Halower";
  });

The alias of the controller gives the routing and instruction a powerful ability to create anonymous controllers. This ability can create a dynamic object as a controller, and the object is isolated and easy to test.

11, require[string or string[]]

Require is the name of a string representing another instruction. Require injects the controller into its specified instruction and acts as the fourth parameter of the link function for the current instruction. The value of a string or array element is the name of the instruction that will be used in the scope of the current instruction. In any case, the NG compiler will refer to the template for the current instruction when looking for a child controller.

If you do not use the ^ prefix, the directive will only find the controller on its own elements. The directive definition only finds the ng-model= "" in the current domain where the instruction is defined.
If you use the? prefix, the required controller is not found in the current instruction, and Null is used as the fourth argument passed to the link function.
If the ^ prefix is added, the directive finds the controller specified by the require parameter in the upstream instruction chain.
If you add? ^ to combine the behavior of the previous two options, we can optionally load the required instructions and find them in the parent instruction chain.
If there is no prefix, the instruction will look in the controller provided by itself, and if no controller (or instruction with the specified name) is found, an error is thrown
12, compile "object or function"

The compile option itself is not frequently used, but the link function is often used. Essentially, when we set the link option, we actually created a postlink () Link function so that the compile () function could define the link function. Normally, if the compile function is set, we want DOM to operate before the instruction and real-time data are placed in the DOM, and it is safe to perform DOM operations such as adding and deleting nodes in this function.

The compile and link options are mutually exclusive. If both options are set, the function returned by compile is treated as a linked function, and the link option itself is ignored.

The compilation function is responsible for converting the template dom. Link functions are responsible for linking scopes and Dom. You can manually manipulate the DOM before the scope is linked to the DOM. In practice, this operation is very rare when writing custom directives, but several built-in directives provide such functionality.

13, Link

Compile:function (TEle, Tattrs, transcludefn) {
 //todo: return
 function (scope, ele, attrs) {
 //link function
 };

Link functions are optional. If a compile function is defined, it returns a linked function, so the compile function overloads the linked function when all two functions are defined. If our instructions are simple and do not require additional settings, you can return a function from the factory function (the callback function) instead of the object. If you do this, the function is the link function.

14, Ngmodel

It provides a more low-level API to handle the data in the controller, which handles data binding, validation, CSS updates, and so on that do not actually manipulate the DOM, and the Ngmodel controller is injected into the instruction with Ngmodel, including some methods. The Require setting must be used in order to access Ngmodelcontroller.

The ngmodelcontroller commonly used elements are as follows:

1. To set the view value in the scope, you need to call the Ngmodel. $setViewValue () function.
$setViewValue () method is appropriate for listening to custom events in custom directives (such as using jquery Plug-ins with callback functions), we would like to set up $viewvalue and perform digest loops on callbacks.

 Angular.module (' myApp ')
    . Directive (' mydirective ', function () {return
      {
        require: '? Ngmodel ',
        Link: function (scope, ele, Attrs, Ngmodel) {
          if (!ngmodel) return;
          $ (function () {
            Ele.datepicker ({
               //callback function
              onselect:function (date) {
                //Set view and invoke apply
                scope.$ Apply (function () {
                  ngmodel. $setViewValue (date);
                });
              }
            );
          });
    

2. $render method can define the specific rendering method of the view
3. Attributes (this property can refer to the end of the previous article for learning)

The above is about the entire content of ANGULARJS instructions, I hope to help you learn.

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.