angular创建独立scope及绑定策略

<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/>'
    }
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值