ANGULARJS instruction Detailed

Source: Internet
Author: User

I. Definition of directives

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

Let's start with a complete sample of the parameters to describe in detail the function and usage of each parameter:

Angular.module (' myApp '), []). Directive (' Mydirective ',function() {     return{restrict:string, Priority:number, Terminal:boolean, template:string or template Function: /c7>function(TElement, Tattrs) {...}, templateurl:string, Replace:boolean or String, Scope:boolean or Object, t Ransclude:boolean, controller:string orfunction(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 functionPostlink (...)         { ... }  }     }; });

Second, the role of the directive parameters and significance (this place only choose a few commonly used to talk about)

Restrict[string]
the 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 an attribute. optional values are as follows: E (Element)A (attribute, default)C (class name)M (note)<--directive:my-directive expression-- >

Generally considering the compatibility of the browser, it is strongly recommended that you use the default property to declare it in the form of an attribute. The last way to do this is not to ask for a force index.

Replace[bool]

Replace is an optional parameter, and if this parameter 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 invokes this instruction.
For example, in the case of the above example default, the resulting HTML code is as follows:

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

If you set Replace=true

<href= "http://www.baidu.com"  value= "http://www.baidu.com" text = "Baidu" > Baidu </a>
Templateurl[string or Function]

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

    • A string representing the path of the external HTML file;
    • A function that can accept two parameters, with arguments of TElement and tattrs, and returns a string of the path to an external HTML file.

Either way, the URL of the template will be passed Ng's built-in security layer, especially $gettrustedresourceurl, which will protect the template from being loaded by untrusted sources. By default, an HTML template file is requested by Ajax in the background when the instruction is invoked. Loading a large number of templates severely slows down the speed of a client application. To avoid delays, you can cache an HTML template before you deploy the app.

    Angular.module (' app ', [])    . Directive (function  () {            return  {                 ' A ',                 function  (Elem, attr) {                    return attr.value + ". html";  // Of course we can specify the path directly, and we can include the expression in the template                 }        };    })

Controller[string or Function]

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

Angular.module (' myApp ', []). Directive (function' A ',  
Replace:true,
' Somecontroller '

An inline controller can be defined within the directive through an anonymous constructor

Angular.module (' myApp ', []). Directive (function' A 'function   ///  controller logic put here }});

We can inject any of the NG services that can be injected into the controller, and we can use it in the instructions. The controller also has some special services that can be injected into the instructions. 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 attributes of the current element.

<id= "Adiv"class= "box"></Div > has the following Property object: {ID: "Adiv", Class: "Box"}

Iii. Scope of Directives

Scope parameter [bool or object]

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

HTML code

 <DivNg-controller= ' Maincontroller 'Ng-init= "myproperty= ' Hello world! '">external: {{MyProperty}}<inputNg-model= "MyProperty" />        <Divmy-directive></Div>    </Div>

JS Code

    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}}<   Ng-model= "MyProperty"/></div>'            };        });

When we change the value of scope we will find

false: inherited but not isolated

1. When we scope set it to false , the instruction we create and the parent scope (which is actually the same scope) share the same model model, so the model data is modified in the directive and it is reflected in the model of the parent scope.

true: inherit and isolate

2. When we scope set it up true , we create a new scope, except that the scope inherits our parent scope;

I think it can be understood that our newly created scope is a new scope, except that the parent scope's properties and methods are used to populate our new scope at initialization time. It is not the same scope as the parent scope.

{}: isolated and not inherited

3. When we scope set it to {} , it means that we create a new scope that is isolated from the parent scope, which allows us to work without knowing the external environment, without relying on the external environment.

Iv. binding Policy

There are typically three binding delivery strategies when using the standalone scope scope, @ One-way pass string = Bidirectional delivery & method for one-way delivery of the parent

 <  inputtype  = "text"  ng-model  = "Myurl"  >  <  div my-directive my-url  = "{{myurl}}"  my-age  = "Age" change-my-age  = "changeage ()  ></ div  >  ① 
 angular.module (' myApp ' ,[]). Directive ( ' mydirective ', function   () { return  { Restrict:  ' A ', //  property mode  replace:< Span style= "COLOR: #0000ff" >true  ,scope:{myurl:  ' @ ', // @ binding policy (default binding to my-url Directive properties)  MyAge: ' = ' //= bidirectional binding   (parent-child interaction) 
changemyage: ' & ' //the method of passing the parent scope
},template: ' <a href= ' {{myurl}} ' Ng-click=changemyage () >{{ MyAge}}</a> ' }});
    • In the above code, I created a directive myDirective that creates two variables Myurl, myLinkText, and both of these variables are used @绑定策略 .

    • To say, whether or not the @ = & binding policy, they all have a default way, with the @ binding policy as an example, as in the above code: myUrl:‘@‘ , directly in a @ way to represent the binding, It defaults to assigning the value of the directive attribute My-url to the Myurl variable .

    • Of course, you do not want to use the default way, that is, you do not want to myurl the value of the variable binding my-url, and you want to bind the value of other property names, then you can @ add the property name you want (the format requirement: Camel style).

    • For example, I want to talk about the value of Myurl bound to the <myDirective></myDirective> Some-attr property of the directive, then you can write: myUrl:‘@someAttr‘ .

    • So we know how the value of the Myurl variable of the instruction is coming, so how do we use it in the template?

    • This is very simple, see the above code can be very clear, we in the code in the template need to use an expression to reference it {{myUrl}} , so that we can use the value of the Myurl variable ~

1. Local Scope properties: Use the @ symbol to bind the local scope to the value of the DOM property, so that the internal scope of the instruction can use the variables of the outer scope:

  You can use a bound string in a directive.

2. Two-way binding: by = You can make two-way data binding on properties on a local scope's property at the half-level scope. Just like normal data binding, local properties reflect changes that occur in the parent data model.
  

3. Parent scope bindings You can bind a parent scope by using the & symbol to run the function in. means that setting this value generates a wrapper function that points to the parent scope.
to invoke a parent method with a parameter, we need to pass an object that is the name of the parameter, and the value is the content to pass to the parameter.

ANGULARJS instruction Detailed

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.