Scope in [angular] directives

Source: Internet
Author: User

The scope parameter has several ways:

1, not filled, default is Scope:false

2,scope:true

3,scope:{}

4,

' =' @ '& ' }

Let me explain the usage between them separately:

The first kind: Look at the code

<script>    Angular module (' Exampleapp ', [])        . Controller(function  ($ Scope) {          //         });        . Directive (function  () {             return  {                 Template:                     "< Div class= ' body ' >name:<input ng-model= ' Name ' ></div> '             }         }' </script>

If scope is not defined here, then angular invokes the default value (Scope:false), where the scope of the instruction is the scope of its parent, where the variables and methods in the parent's role can be called;

Such as:

<script type="Text/javascript">Angular.module ("Exampleapp", []). Directive ("Scopedemo", function () {return{template:function () {returnangular.element (Document.queryselector ("#scopeTemplate") . html (); }, Link:function (scope, element, attrs) { scope.func (); //call the method in the parent controller;}} ). Controller ("Scopectrl", Function ($scope) {$scope. Data= {Name:"Adam" }; $scope. City="London"; $scope. Func =function () {alert ('You can call me!');    }        }); </script>

The second kind: Look at the code

JS section:

<script type= "Text/ng-template" id= "scopetemplate" > <div class= "panel-body" > <p>name: <inpu T ng-model= "Data.name"/></p> <p>city: <input ng-model= "City"/></p> <p>Cou Ntry: <input ng-model= "Country"/></p> </div></script><script type= "Text/javascript" >Angular.module ("Exampleapp", []). Directive ("Scopedemo",function () {            return{Template:function() {                        returnangular.element (Document.queryselector ("#scopeTemplate") . html (); }, scope: true , Link:function(scope, element, Attrs) {scope.func (); }}). controller ("Scopectrl",function($scope) {$scope. Data= {Name: "Adam" }; $scope. City= "London"; $scope. Func=function() { alert ( ' OK '); }        });
</script>

HTML section

<body ng-controller= "Scopectrl" >    <div class= "Panel Panel-default" >        <div class= "Panel-body" scope-demo></div>        <div class= "Panel-body" scope-demo></div>    </div></body >

This command is called in two places in HTML, but the production effect is not the same, at run time

The effect is that name is synchronous (changing up and down any other one will change), City and country are independent, and the next two changes will not affect the other;

The reason is that scope:true allows us to create a new scope in the same controller, but this scope is the property and method that can inherit the scope of its parent, then it is not the same as the scope, it is not, because he created his own scope, Then his freedom will be better than not write scope, then why some can change together dynamically, and some cannot, then look at their data properties:

<div class= "Panel-body" >    <p>name: <input ng-model= "Data.name"/></p>    <p>City : <input ng-model= "City"/></p>    <p>country: <input ng-model= "Country"/></p></ Div>
In the controller:
. Controller ("Scopectrl", function ($scope) {            $scope. data = {name: "Adam" };            $scope. City = "London";            $scope. Func = function () {                alert (' OK ');}});    
Name Describe
Data.name This property is defined on an object, meaning that the value will be shared between instances in the instruction, and all input box elements bound to that property will remain in sync
City This property is assigned directly on the controller's scope, meaning that all scopes of the instruction begin with the same initial value, but when the input box element is modified, it creates and modifies its own version on its own scope.
Country This property is not assigned any value, and when the corresponding input box element is modified, each instance of the instruction will create a separate county property.

The Third kind: look at the code

<script type= "Text/javascript" >Angular.module ("Exampleapp", []). Directive ("Scopedemo",function () {                return{Template:function() {                        returnangular.element (Document.queryselector ("#scopeTemplate") . html (); }, scope: {} }}). controller ("Scopectrl",function($scope) {$scope. Data= {Name: "Adam" }; These two methods will not be passed to the directive for use $scope. City= "London";    }); </script>

scope:{} tells angular that this directive creates a separate (isolated) scope so that this independent scope cannot inherit the scope of the outside parent controller. The advantage of this is that the instruction will not contaminate the outside parent scope when it is re-invoked.

Fourth type

The fourth is the third way of hardening, that is, although my scope is isolated from the outside world, there are some parameters (values, attributes, methods) to be obtained from the outside world. So how do we get it,

Angular provides three ways for us to use, respectively, ' = ', ' @ ', ' & ', and their roles are:

@: Binding through the property values, but one-way, that is, the external controller can pass the value in for internal use, but the internal modification of this property value will not affect the external;

JS section

<script type= "Text/ng-template" id= "scopetemplate" > <div class= "panel-body" > <p>data V Alue:{{Local}}</p> </div> </script> <script type= "Text/javascript" >Angular.module ("Exampleapp", []). Directive ("Scopedemo",function () {                return{Template:function() {                        returnangular.element (Document.queryselector ("#scopeTemplate") . html (); }, Scope: { Local: "@nameprop"}} ). Controller ("Scopectrl",function($scope) {$scope. Data= {Name: "Adam" };    }); </script>

HTML section

<body ng-controller= "Scopectrl" >    <div class= "Panel Panel-default" >        <div class= "Panel-body" >            <input ng-model= "Data.name"/>//change here will follow the change        </div>        nameprop= "{{ Data.name}} "></div>//Follow the above values dynamically    </div></body>

The local in the directive obtains the external attribute data.name through the nameprop, so when the data.name in the controller changes, the local in the instruction will change as well, (but if the local value is changed only, the outside Data.name will not change);

=: two-way data binding through attributes, internal and external changes will be consistent;

JS section

<script type= "Text/ng-template" id= "scopetemplate" > <div class= "panel-body" > <p>data V Alue: <inputng-model= "Local"/></p> </div> </script> <script type= "Text/javascript" >Angular.module ("Exampleapp", []). Directive ("Scopedemo",function () {                return{Template:function() {                        returnangular.element (Document.queryselector ("#scopeTemplate") . html (); }, Scope: { Local: "=nameprop"}} ). Controller ("Scopectrl",function($scope) {$scope. Data= {Name: "Adam" };    }); </script>

HTML section

<body ng-controller= "Scopectrl" >    <div class= "Panel Panel-default" >        <div class= "Panel-body" >            <input ng-model= "Data.name"/>        </div>        nameprop= "Data.name"> </div>    </div></body>

Show the effect:

Both the instruction and the controller use the Local: "=nameprop" for two-way data binding;

&: Call a method (function) in the parent scope;

JS section

<script type= "Text/ng-template" id= "scopetemplate" > <div class= "panel-body" > <p>name: {{Local}}, City: {{cityfn ()}}</p> </div> </script> <script type= "Text/javascript" >Angular.module ("Exampleapp", []). Directive ("Scopedemo",function () {                return{Template:function () {                        returnangular.element (Document.queryselector ("#scopeTemplate") . html (); }, Scope: {Local:"=nameprop", cityfn: "&city"}} ). Controller ("Scopectrl",function($scope) {$scope. Data={name:"Adam", defaultcity:"London"            }; $scope. getcity =function(name) {returnName = = "Adam"? $scope. Data.defaultcity: "Unknown";    }        }); </script>

HTML section

<body ng-controller= "Scopectrl" >    <div class= "Panel Panel-default" >        <div class= "Panel-body" >            <input ng-model= "Data.name"/>        </div>        <div class= "Panel-body" scope-  Demo              City= "getcity (data.name)" nameprop= "Data.name" ></div>    </div ></body>

The value of the city attribute is an expression that invokes the getcity behavior and passes the Data.name property as a parameter for processing. To make this expression available in the isolation scope, add CITYFN: "&city", prefix ' & ' in scope to tell angular that I want to bind the value of the specified attribute (CITYFN) to a function, leaving the function expression to be called in the instruction: {{CITYFN ()}}

PS: Here all instruction scopes interact with the outside world via attribute values : <div class= "Panel-body" Scope-demo City =" Getcity (data.name) " nameprop=" Data.name "></div>

Scope in [angular] directives

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.