Instruction Practice Development Guide in AngularJS (2) _ AngularJS

Source: Internet
Author: User
This article mainly introduces the instructions in AngularJS (2). For more information, see instructions in AngularJS (1, how to isolate the scope of an instruction. The second part will continue with the previous article. First, we will see how to access the attributes of the parent scope from inside the instruction while using the isolated scope. Next, we will discuss how to select the correct scope for the command based on the controller function and transclusions. At the end of this article, we will use a complete notepad application to practice instructions.

Isolate data binding between scope and parent scope

Generally, the scope of the isolation command brings a lot of convenience, especially when you want to operate multiple scope models. But sometimes in order to make the code work correctly, you also need to access the attributes of the parent scope from within the instruction. The good news is that Angular gives you enough flexibility to selectively pass in attributes of the parent scope through binding. Let's review our helloWorld command. Its background color changes with the color name entered in the input box. Remember when we use an isolated scope for this command, it will not work anymore? Now let's restore it to normal.

Suppose we have initialized the Angular module pointed to by the app variable. The following code shows the helloWorld command:

app.directive('helloWorld', function() {return {scope: {},restrict: 'AE',replace: true,template: '

Hello World

',link: function(scope, elem, attrs) {elem.bind('click', function() {elem.css('background-color','white');scope.$apply(function() {scope.color = "white";});});elem.bind('mouseover', function() {elem.css('cursor', 'pointer');});}};});

The HTML Tag using this command is as follows:

 

The above Code cannot work now. Because we use an isolated scope, the {color} expressions in the instruction are isolated from the scope (not the parent scope) in the instruction ). However, the ng-model command in the input box element points to the color attribute in the parent scope. Therefore, we need to bind the two parameters in the isolation scope and parent scope. In Angular, this type of data binding can be achieved by adding attributes to the HTML element where the directive is located and configuring the corresponding scope attributes in the directive definition object. Let's take a closer look at several data binding methods.

Option 1: Use @ to bind one-way text

In the following command definition, we specify the colorAttr parameter for binding the attribute color in the isolated scope to the HTML element of the instruction. In the HTML Tag, you can see that the {color} expression is specified to the color-attr parameter. When the expression value changes, the color-attr parameter also changes. The value of the color attribute in the quarantine scope is also changed.

app.directive('helloWorld', function() {return {scope: {color: '@colorAttr'},....// the rest of the configurations};});

The updated HTML Tag code is as follows:

 

This method is called single-item binding because in this method, you can only pass strings (using expressions {{}}) to parameters. When the attributes of the parent scope change, the attribute values in your isolated scope model change. You can even monitor the changes to the scope attribute inside the command and trigger some tasks. However, reverse transfer does not work. You cannot change the value of the parent scope by operating the isolate scope attribute.

Note:

When the isolation scope attribute is the same as the command element parameter name, you can set scope binding in a simpler way:

app.directive('helloWorld', function() {return {scope: {color: '@'},....// the rest of the configurations};});

The HTML code of the corresponding instruction is as follows:

 

Option 2: Use = to implement bidirectional binding

Let's change the definition of the command to the following:

app.directive('helloWorld', function() {return {scope: {color: '='},....// the rest of the configurations};});

The corresponding HTML modification is as follows:

 

Unlike @, This method allows you to specify a real scope data model for attributes, rather than a simple string. In this way, you can pass simple strings, arrays, and even complex objects to the isolated scope. Two-way binding is also supported. When the parent scope attribute changes, the attribute in the corresponding isolated scope also changes, and vice versa. As before, you can also monitor the changes to this scope attribute.

Select 3: Use & execute the function in the parent scope

Sometimes it is necessary to call the functions defined in the parent scope from the isolated scope. To access the functions defined in the external scope, we use &. For example, we want to call the sayHello () method from inside the command. The following code tells us how to do this:

app.directive('sayHello', function() {return {scope: {sayHelloIsolated: '&'},....// the rest of the configurations};});

The corresponding HTML code is as follows:

 

This Plunker example provides a good explanation of the above concepts.

Differences between parent scope, subscope, and isolated scope

As a newbie to Angular, you may be confused when choosing the correct command scope. By default, the command does not create a new scope, but follows the parent scope. But in many cases, this is not what we want. If your command heavily uses the attributes of the parent scope, or even creates new attributes, parent scope will be contaminated. It is not a good idea to allow all commands to use the same parent scope, because anyone may modify the attributes in this scope. Therefore, the following principle may help you select the correct scope for your instructions.

1. Parent scope (scope: false)-this is the default situation. If your command does not operate the attributes of the parent scoe, you do not need a new scope. In this case, the parent scope can be used.

2. Sub-scope (scope: true)-This creates a new scope for the instruction and the prototype inherits from the parent scope. If the attributes and methods in your instruction scope have no relationship with other instructions and the parent scope, you should create a new scope. In this way, you also have the attributes and methods defined in the parent scope.

3. Isolate scope (scope :{})-This is like a sandbox! When the commands you create are self-contained and reusable, you need to use this scope. You will create many scope attributes and methods in the command. They are only used inside the command and will never be known to the outside world. If so, the isolated scope is a better choice. The isolated scope does not inherit the parent scope.

Transclusion (embedded)

Transclusion is a method that allows our commands to contain arbitrary content. We can extract the embedded content in a delayed manner and compile the embedded content in the correct scope, and finally put them into the location specified in the instruction template. If you set transclude: true in the Command definition, a new embedded scope will be created, and its prototype inherits the sub-parent scope. If you want your command to use an isolated scope, but the content contained in it can be executed in the parent scope, transclusion can also help.

Suppose we register the following command:

app.directive('outputText', function() {return {transclude: true,scope: {},template: '

'};});

It uses the following:

Hello {{name}}

Ng-transclude indicates where the content is embedded. DOM content in this example

Hello {name }}

Extracted and placed

Internal. It is important to note that the attribute of the expression {name} is defined in the parent scope, rather than the subscope. You can do some experiments in this Plunker example. If you want to 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.