您的位置:首页 > 运维架构

angular创建独立scope及绑定策略

2017-11-07 16:58 288 查看
<body>
<hello></hello>
<hello></hello>
<hello></hello>
<hello></hello>
</body>

var myModule = angular.module("MyModule", []);

myModule.directive("hello", function() {

    return {

        restrict: 'AE',

        scope:{},//创建独立scope,四个hello指令之间互不影响

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

        replace: true

    }

});

scope有三种绑定策略:@  =  &

@绑定字符串

=进行双向绑定

&调用父scope中函数

1、@

<body>
<div ng-controller="MyCtrl">
<drink flavor="{{ctrlFlavor}}"></drink>
</div>

</body>

var myModule = angular.module("MyModule", []);

myModule.controller('MyCtrl', ['$scope', function($scope){
$scope.ctrlFlavor="百威";

}])

myModule.directive("drink", function() {

    return {

    restrict:'AE',

        scope:{//有了这句则link可省略

        flavor:'@'

        },


        template:"<div>{{flavor}}</div>"

        // ,

        // link:function(scope,element,attrs){

        // scope.flavor=attrs.flavor;

        // }

    }

});

2、=

<body>
<div ng-controller="MyCtrl">
Ctrl:
<br>
<input type="text" ng-model="ctrlFlavor">
<br>
Directive:
<br>
<drink flavor="ctrlFlavor"></drink>
</div>

</body>

var myModule = angular.module("MyModule", []);

myModule.controller('MyCtrl', ['$scope', function($scope){
$scope.ctrlFlavor="百威";

}])

myModule.directive("drink", function() {

    return {

    restrict:'AE',

        scope:{

        flavor:'='

        },


        template:'<input type="text" ng-model="flavor"/>'

    }

});

3、&(之前通过指令属性的方式进行控制器与指令的绑定,现在可用&)

<body>
<div ng-controller="MyCtrl">
<greeting greet="sayHello(name)"></greeting>
<greeting greet="sayHello(name)"></greeting>
<greeting greet="sayHello(name)"></greeting>
</div>

</body>

var myModule = angular.module("MyModule", []);

myModule.controller('MyCtrl', ['$scope', function($scope){
$scope.sayHello=function(name){
alert("Hello "+name);
}

}])

myModule.directive("greeting", function() {

    return {

    restrict:'AE',
        scope:{

        greet:'&'

        },


        template:'<input type="text" ng-model="userName" /><br/>'+

        '<button class="btn btn-default" ng-click="greet({name:userName})">Greeting</button><br/>'

    }

});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: