How to understand the scope attribute of angular custom directive directive?

Contents 1. Background

2. Knowledge analysis

3. Frequently Asked Questions

4. Solutions

5. Coding

6. Expand your thinking

7. References

8. More discussion

1. Background Describes the instruction definition

The biggest difference between AngularJS and JQuery is two-way data binding, which essentially means DOM manipulation.

JQuery uses selectors to find DOM elements and assign them behavior. AngularJS, on the other hand, binds directives to the DOM and extends the behavior of directives. For example, ng-click allows an element to listen for a click event and perform AngularJS table accesses when the event is received. We can create new instructions ourselves. Use the Angular module directive() to define directives.Copy the code

2. Knowledge analysis of the contents of a complete custom instruction

angular.module(…) ;

.directive('My-directive', function(injectables){ restrict: 'A', &emsp; &emsp; priority: 0, &emsp; &emsp; template: '<div></div>', &emsp; &emsp; templateUrl: 'directive.html', &emsp; &emsp; replace: false, &emsp; &emsp; transclude: false, &emsp; &emsp; scope: false, &emsp; &emsp; compile: function(tElement, tAttrs, transclude){ &emsp; &emsp; &emsp; &emsp; return{ &emsp; &emsp; &emsp; &emsp; &emsp; &emsp; Pre: function preLink(scope, iElement, iAttrs, controller){... }, &emsp; &emsp; &emsp; &emsp; &emsp; &emsp; Post: function postLink(scope, iElement, iAttrs, controller){... } &emsp; &emsp; &emsp; &emsp; } &emsp; &emsp; }, &emsp; &emsp; link: function(scope, iElement, iAttrs){ ... }Copy the code

});

Restrict (String)

Restrict is an optional parameter. It tells AngularJS how the directive can be declared in the DOM. By default AngularJS considers RESTRICT to be A, which is declared as an attribute.

Restrict values can be any of the following:

E is used as the element name

A is used as an attribute

C is used as the class name

M is used as a comment

Template (string or function)

The template argument is optional and must be set to one of two forms:

 a piece of HTML text;

 A function that takes two arguments, tElement and tAttrs, and returns a string representing the template.

TemplateUrl, importing an external HTML file

SCOPE in instruction

By default, directive shares properties defined in the parent scope, such as using objects and properties from the parent scope directly in templates. Simple directive functions can often be implemented using this direct sharing approach. However, when creating a directive that can be reused, you cannot rely on the parent scope, because the parent scope of a directive is different in different places. So you need an isolated scope.Copy the code

2.2 Three values of scope attribute

False (default) : Use the parent scope directly.

② true: inherits the parent scope

Object {} : create a new “isolated” scope, but still communicate with the parent scope. Isolated scopes are usually used to create reusable instructions, that is, they do not care about the model in the parent scope. However, although it is said to be “isolated”, we usually need to bind the child scope to the variables in the parent scope. There are three binding policies: @, =, and &.

@ This is a prefix identifier for a single binding

My-name =”{{name}}”; note that the name of the attribute is used to connect the two words, because it is a single binding of data, so it is used to bind data with {{}}.

= This is a bidirectional data binding prefix identifier

Use: use attributes in elements, such as my-age=”age”. Note that bidirectional binding of data is implemented with the = prefix identifier, so {{}} is not allowed.

& This is the prefix identifier of a binding function method

How to use it: Use attributes in elements, such as my-change=”changeAge()”, notice that the name of the attribute is linked with multiple words.

CONTROLLER, COMPILE, LINK functions in the directive

AngularJs lifecycle; There are two stages:

The first phase is the compile phase: During the compile phase, AngularJS iterates through the HTML document and processes the instructions declared on the page according to the instructions defined in JavaScript.

Each directive template may contain another directive, and another directive may have its own template. When AngularJS calls the directive at the root of an HTML document, it iterates through all the templates in the document. Templates may also contain directives with templates. Once the instruction and its subtemplates are iterated or compiled, the compiled template returns a function called a template function. We have the opportunity to modify the compiled DOM tree before the directive's template function is returned.Copy the code

The second stage is the link stage: link functions to link templates to scopes; Responsible for setting up event listeners, monitoring data changes and manipulating the dom. link functions are optional.

If a compiler function is defined, it returns the link function, so when both functions are defined, the compiler function overloads the link function

The controller and link functions of the instructions are interchangeable. Controllers are primarily used to provide behavior that can be reused between instructions, but link functions can only define behavior within the current internal instructions and cannot be reused between instructions. Link functions isolate instructions from each other, while controllers define reusable behavior.Copy the code

3. Common Questions What is the impact of the three values of scope attribute on instructions?

Whenever an instruction is created, it has the choice of inheriting its parent scope (typically the scope provided by an external Controller or the rootScope ($rootScope)), or creating a new scope of its own. Of course AngularJS provides three options for the scope argument of our directive: false,true,{}; The default is false.

What happens when the scope argument is set to false when a parent scope variable, function, can be used directly in an instruction template

Ctrl:<br> <input ng-model="userName">{{userName}}<br> Directive:<br> <hello></hello> <br> <hello></hello> </div> Angular. module("app",[]) // Tests true and falseCopy the code

.controller(“MyCtrl”,function($scope){

$scope. The userName = "landscape";Copy the code

})

                    .directive("hello",function() {
Copy the code

return{

                            restrict:"AECM",

                            template:'<div><input type="text" ng-model="userName">{{userName}}</div>',
Copy the code

replace:true,

scope:false }

})

Because we set the scope property to false, the directive we create inherits all properties and methods of the parent scope, which makes it possible to use these properties and methods in the directive template.

Note: When we change the name in the input box, we will find that the two names above have changed

4.2 scope = true.

When the scope property is set to true, it indicates that the directive we created creates a new scope that inherits from our parent scope.

Change: scope:false to scope:true

Then we try to write some strings in our input box, and we find that the name in the instruction changes, but the name outside the instruction doesn’t, which tells us something.

When we set scope to true, we create a new scope that inherits from our parent scope. I think it can be understood that our newly created scope is a new scope, but when initialized, we fill our new scope with the properties and methods of the parent scope. It’s not the same scope as the parent scope.

When we set scope to false, the directive we create shares the same model as the parent scope, so when we modify the model data in the directive, it is reflected in the parent scope’s model.

4.3 the scope = {}

We can do a lot more when we set the scope property to {}.

One of the great things about AngularJS is that it can build components that can be used wherever you put them; This is possible because of this property of the instruction; When we set scope to {}, it means that we create a new scope that is isolated from the parent scope, which allows us to function without being aware of the external environment.

Just because we use isolated scopes doesn’t mean we can’t use properties and methods in the parent scope.

We can bind data by passing a special prefix identifier (i.e. Prefix) to scope {}.

In the isolated scope, we can refer to the attributes of the element to which the directive applies via @,&,=

Let’s look at how to use these prefix identifiers:

1.@ : one-way binding, the external scope can affect the internal scope, but the reverse is not true;

This is a prefix identifier for a single binding. Usage: Use attributes in elements, like this

Note that the name of the property is concatenated with -, since this is a single binding of data, the data is bound with {{}}.

2, = : bidirectional binding, the model of external scope and internal scope can change each other;

This is a bidirectional data binding prefix identifier. Usage: Use attributes in elements, like this

Note that bidirectional binding of data is implemented with the = prefix identifier, so {{}} cannot be used.

3, & : bind the return value of the function of the inner scope to any properties of the outer scope.

This is the prefix identifier of a binding function method. Usage: Use attributes in elements, like this

Note that the name of the property is concatenated with multiple words.

How do our instructions use these prefix identifiers to find desired attributes or functions?

When the @ directive is compiled into the template’s name, it will look into the scope to see if there is a key-value pair containing name. If there is, as above, it will know that the @ directive is a one-way data binding. Then look for the attribute on the original directive element (or the directive element itself) that contains this value, namely my-name={{name}}. Then look for the value of {{name}} in the parent scope and pass it to the name in the template.

= is similar to & and @, except that = is two-way data binding, and any change in the value of an attribute in the template or parent scope changes another value, while & is a binding function.

Reference 1: AngularJS custom directives

Play with the Scope of AngularJS directives

More discussion Thanks for watching

Today’s share is over here, welcome everyone to like, forward, leave a message, pat brick ~

Skill tree.IT Monastery

“We believe that everyone can become an engineer. From now on, find a senior to guide you to the entrance, control the pace of your own learning, and no longer feel confused on the way to learning.”

Here is the skill tree.IT Shuzhen Institute, where thousands of brothers find their own learning route, learning transparent, growth visible, brothers 1 to 1 free guidance.

Come with me learn ~ http://www.jnshu.com/login/1/21109035