The Directive--scope option and binding policy of angular learning experience

Source: Internet
Author: User

To put it bluntly, scope:{} separates the instruction from the outside world, leaving its template in a non-inheriting (no inheritance) state, unless, of course, the notes are recorded in detail until you use transclude embedding in it. But this is obviously not in line with actual development requirements, because in fact, we often want our instructions to be able to interact with the outside world in certain situations, which requires the help of a binding strategy.

As you know, when the scope option is written in this form of scope:{}, the isolation scope has been generated for the directive, and now we look at the three forms of the binding strategy:&, =, @.

The first is @, which binds the property values in the local scope and DOM (and the value of this property must be in the scope of the parent), what does it mean? The simple thing to say is that you have a double curly brace expression in the template, and then we bind the content in the expression to the properties of the specific name in the instruction in the HTML, or do we not understand? Take a look at the following code:

JS Code:

directive ("direct", function () {return{restrict: ' ECMA ', Template: ' <div> directive: {{name}}} </div> ', scope:{name: ' @forName '}}). controller ("Namecontroller", fun Ction ($scope) {$scope. Name= "Zhang San"; });

HTML code:

<div ng-controller= "Namecontroller" > <direct for-name= "{{name}}" ></direct><div>

As you could imagine, {{name}} was successfully bound to name in the parent controller. Of course, it can be written here.

Name: ' @ ' In this case, the default DOM property name name means that for-name= "{{name}}" can be abbreviated to Name= "{{name}}"; In fact, the other two symbols = and & also have such shorthand rules, For convenience, use this notation for the next step.

@ That's it, next is ' = '. The difference between = and @ is that @ is used for strings, but = is a reference to an object,

This may not be professional, but take the example above, we in the HTML, the name of the string is passed through a pair of curly braces to the For-name property, but if we use =, the name passed here should not be a string, but a reference to an object. This is not a very straightforward concept, so I'll use the next two examples to illustrate its meaning.

First example: reference to an object in an array

JS Code:

directive ("direct", function () {return{restrict: ' ECMA ', Template: ' <div> directive: {{Case.na Me}}</div> ', scope:{case: ' = '}}}. controller ("Namecontroller", funct Ion ($scope) {$scope. Data=[{name: "Zhang San"},{name: "John Doe"}];});

HTML code:

<div ng-controller= "Namecontroller" > <direct case= "data[0]" ></direct> <direct case= "data[1]" ></direct> <div>

The result is a Zhang San, a John Doe. In this example, data is an array of objects containing two objects, so we pass two objects to the case property, which passes the reference of the object to the case in the template we wrote in {{case.name}}, and if you are in the = With the name you define in the back, just replace the case attribute in the HTML with that name.

The second example: a classic bidirectional input box

According to Angular's introductory case, create two two-way bound input boxes, the simplest way to achieve this is:

<input ng-model= "test"/> <input ng-model= "test"/>

You can do it with the Ng-model command. Next, we implement this effect in our own instructions.

JS Code:

directive ("direct", function () {return{restrict: ' ECMA ', Template: ' <div> directive: <input Ng-model= "model"/></div> ', scope:{model: ' = '}}}). controller ("Name Controller ", function ($scope) {$scope. Data=[{name:" Zhang San "},{name:" John Doe "}];});

HTML code:

<div ng-controller= "Namecontroller" > Parent scope: <input ng-model= "Mark"/> <direct model= "Mark"/ ></direct> </div>

This is done, in fact, just add a little trick, the Ng-model replaced the model.

Note that in these two examples, the reference to the object is used, rather than the simple string, which is also the key to the two-way binding.

Finally, the & symbol. The implication is that the parent scope is bound and the properties are wrapped into a function, note that the attribute, that is, any type of property will be wrapped into a function, such as a simple string, or an object array, or a function method, if it is a string, Arrays of objects and functions without parameters, it is conceivable that they will be packaged as a function without parameters, if the function method of the argument is opposite, and we need to pass in an object for it. Now, for example, there are two cases of both parameter and no reference.

No information ↓

js Code:

. directive ("direct", function () {        return{             restrict:  ' ECMA ',             template:  ' <div>{{ title }}</div> ' + ' <div> <ul><li ng-repeat= "X in contents" >{{ x.text }}<                         /li></ul></div> ',              scope:{                               gettitle: ' & ',                getcontent: ' & '                       },             controller:function ($scope) {                  $scope. title=$ Scope.gettitle ();      //call no argument function                    $scope. contents= $scope. getcontent ()     // Call the parameterless function             }        }  }). controller ("Namecontroller", Function ($scope) {     $scope. title= "title";     $scope. contents =[{text:1234},{text:5678}]; });

HTML code:

<div ng-controller= "Namecontroller" > <direct get-title= "title" get-content= "Contents" ></direct> & Lt;/div>

This example has several points to note:

1. The local properties of the directive (that is, the attributes in the curly brackets in the template) require a local value, so the controller option is used, and in the controller option, two non-parametric methods return the title string and the contents object array in the parent scope, respectively.

2. In HTML, we set the attribute values for Get-title and get-content to title and contents, which actually completes the binding to the parent scope, because we can get the actual content from there.

OK, there is a situation ↓

JS Code:

. directive ("direct", function () { return{             restrict:  ' ECMA ',             template:   ' <div><input ng-model= ' model "/></div> ' + ' <div><button ng-click=" show ({Name:model}) ' >show</button> ',             scope:{                 Show: ' & '                            }                                 }    })     .controller ("NameController", function ($scope) {         $scope. Showname=function (name) {             alert (name);           }      });

HTML code:

<div ng-controller= "Namecontroller" > <direct show= "showname (name)" ></direct> </div>

In this example, the show function is triggered by Ng-click in the template and an object called model is passed in as the name parameter, whereas in HTML we set the property value of Show to ShowName (name). The truth of this is similar to the example of no argument.

The binding strategy for,@,=,& is probably the way it is. What needs to be supplemented and corrected, I implore you the great God to me, thank you!

The Directive--scope option and binding policy of angular learning experience

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.