Angulajs detailed concept of scope in directive

Source: Internet
Author: User

Directive is the most important concept in angularjs, my understanding is to customize the HTML tag, this custom tag browser will not parse, there will be angularjs to dynamically parse.

For example in the HTML add <mypannel title= "title" description= "Pannel description" ></MYPANEL> This mypannel tag browser obviously does not know, This is actually a directive. This directive we have to define in the JS code and set the displayed HTML template for it to be displayed on the page normally.

This article will assume that you already know the concept of Directive and know how to create a custom directive. For this part of the content, this article does not introduce, this article mainly introduces in the custom directive a very important attribute scope.

When Angularjs is started, a Rootscope object is created automatically. When you create a controller and directive, you automatically create your own private scope object, and the private scope inherits from Rootscope.

Scope in the Directive

All directives have their own scope object. By default, directive does not create their own scope.  They will use the scope of their parent as their scope. But ANGULARJS allows this default behavior to be changed.

such as the following example:

var app = Angular.module ("MyAPP", []); App.directive ("myspan " , function () {  return  {      "EA",       true,      link:function (scope,elem,attr) {          }}}     );

The above code we create a directive named MySpan. There is a scope property, and we set the value to true. This property can be set to one of the following values, true, Flase, or {}.

Below we will accept that these three are worth a difference.

Differences in Directive scope values

Scope:false (Directives will use the scope of parent), this is the default value

Look at the following:

1. HTML code

<div ng-app="myapp">        <div ng-controller="Ctrl1" >        

"changename ()">hey {{name}}, click me to Reinit name Class='directive'></div> </div ></div>

2. Js Code

varApp = Angular.module ("MyApp", []); App.controller ("CTRL1", Function ($scope) {$scope. Name="Slardar"; $scope. ChangeName=function () {$scope. Name + = "_";    };}); App.directive ("mydirective", function () {return{restrict:"EA", Scope:false, Template:"<div>your name is: {{name}}</div>"+"Change your name: <input type= ' text ' ng-model= ' name '/>"    };});

3. css

h2 {    cursor:pointer;}. directive {    border:5px solid #F5BF6E;    padding:10px;}

Preview Address: http://jsfiddle.net/od3a4ddw/9/

As you can see, the Name property inside the directive and the name inside the controller is an object. This means that directive uses the scope object of its parent as its scope object. When you change the value of the name object in the controller, the name of Directive is updated, and the Name property is updated in directive, and the name in the controller is updated. Because they are actually an object.

Scope:true (directives will create a new scope, but the scope created will inherit from the scope object in the parent controller.) )

When set to false, Directive uses the scope object of the parent object, set to True to create a scope object, but inherits from the parent's scope object. These two sentences seem a little difficult to understand.

We modify the JS code above to set the scope object to True

varApp = Angular.module ("MyApp", []); App.controller ("CTRL1", Function ($scope) {$scope. Name="Slardar"; $scope. ChangeName=function () {$scope. Name + = ' _ ';    };}); App.directive ("mydirective", function () {return{restrict:"EA", Scope:true, Template:"<div>your name is: {{name}}</div>"+"Change your name: <input type= ' text ' ng-model= ' name '/>"    };});

Preview Address: http://jsfiddle.net/od3a4ddw/10/

Click inside the header, you can see in the directive name and controller name in the same time is changing (that is, at this time, directive inside the name object is directly obtained from the parent object (the reason for inheritance). But when we entered the textbox in Directive, we found that the modification to the name object no longer affected the Name property of Parentscope. This is because the name object inside the directive is created after the onchange event inside the text box is triggered. That is, Directive creates its own name object after the text onchange event occurs. Also at this time click the header again to discover that the name value inside the directive is no longer affected by the name in the parent scope.

Scope: {} (directives creates a new isolation scope, which is not inherited from the parent scope object)

This officially recommended way to write scope so that the objects in the directive and the parent object interact with each other, but because the new quarantined object created is a completely new empty object, assigning a value to this object becomes a problem.

Look at the following:

Modify the JS code as follows

varApp = Angular.module ("MyApp", []); App.controller ("CTRL1", Function ($scope) {$scope. Name="Slardar"; $scope. ChangeName=function () {$scope. Name+="-"; };}); App.directive ("mydirective", function () {return{restrict:"EA", scope: {}, Template:"<div>your name is: {{name}}</div>"+"Change your name: <input type= ' text ' ng-model= ' name '/>"    };});

Preview Address: http://jsfiddle.net/qggdk7gg/

From the above list, you can see that when you click on the header text, direct inside name is always empty, because the scope inside the directive is an isolated scope, which knows nothing about the scope variable of parent.

However, we can pass values from the parent object to directive in the following way.

There are three ways to pass the value:

By means of the @ Pass value (string binding, one way binding (unidirectional bound), which is to pass the string to Directive for display), when calling directive, you need to use {{}} for attribute to pass the value.

by = pass value (model binding, two way bingding (bidirectional binding)) when calling directive, you need to use the model name for attribute to pass the value.

Pass & Pass Value (method binding)

Here's a complete look:

1. HTML code

<div ng-app="app"> <divclass="Parent"Ng-controller="Mainctrl"> <divclass=" Line">Name inside parent Scope is: <strong>{{name}}</strong> <input type="Button"ng-click="changename ()"Value="Change name"/> </div> <divclass=" Line">titleinchParent scope is: {{title}}<input type="Button"ng-click="Changetitle ()"Value="Change title"/> </div> <divclass="Directive"my-directive name="{{name}}"title="title" Change-name="changename ()"></div> </div></div>

2. JS Code

varApp = Angular.module ("app", []); App.controller ("Mainctrl", Function ($scope) {$scope. Name="Slardar"; $scope. Title="Slardar_title"; $scope. ChangeName=function () {$scope. Name+='_';    }; $scope. Changetitle=function () {$scope. Title+='_'; }}); App.directive ("mydirective", function () {return{restrict:"EA", scope: {name:"@", Title:"=", ChangeName:"&"}, Template: ["<div class= ' line ' >",            "Title: <strong>{{title}}</strong>;<br/>name: <strong>{{name}}</strong>; Change name:<input type= ' text ' ng-model= ' name '/><br/>",            "</div><div class= ' line ' >",                       "<br/><input type= ' button ' ng-click= ' ChangeName () ' value= ' Change Name '/>"].join ("")        };});

3. Css

. Parent {border:20px solid #676767; padding:20px;}. parent,.directive {position:relative;}.    parent:after,.directive:after {display:inline;    Color: #fff; Font-Size:normal;    Position:absolute; Top:-20px; Left:-20px; Z-index: -;    PADDING:1PX 5px; Background-color:rgba (0,0,0,0.5);}. Parent:after {content:"Mainctrl Scope";}.    directive {padding:20px;    border:20px solid #cbccdd; Margin-top:20px;}. Directive:after {content:"Directive Scope"}.line {Border-bottom:1px dotted #ccc; padding:5px0;}

Full Demo Address: http://jsfiddle.net/g5kdns5x/1/

The above can be seen to see the complete directive definition

class="directive" my-directive            name="{{name}}"  "            title="title"            Change-name=  "changename ()"        ></div>

Where the name attribute defines a one-way string binding with @, followed by an assignment using the {{}}. Sake just passes the Name property value in Directive, which is.

Title uses = To define the model bindings, followed by the property names in scope. Sake passes the title model into directive, and the title model is modified in direct to synchronize to the title of the parent object.

Change-name with & definition, method binding. Directly followed by the method call. In the example, the ChangeName method is passed to directive inside, so that the ChangeName method defined inside the parent object can be used inside the directive.

Well, the above is my introduction to the definition of scope in directive, I hope that everyone's study has helped.

Angulajs detailed concept of scope in directive

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.