Lel*_*uch 11 angularjs angularjs-directive angularjs-scope
我学习AngularJS指令,并有一件事我想要做的是通过一些变量$scope.message在父scope(一scope的controller),我希望它被重新命名为param里面的directive alert.我可以用一个孤立的范围做到这一点:
<div alert param="message"></div>
Run Code Online (Sandbox Code Playgroud)
并定义
.directive("alert", function(){
return{
restrict: "A",
scope: {
param: "="
},
link: function(scope){
console.log(scope.param) # log the message correctly
}
}
})
Run Code Online (Sandbox Code Playgroud)
但是,如果不使用隔离范围,我可以做到吗?假设我要另加directive toast到<div toast alert></div>与使用相同param(保持2路数据绑定),天真的我会做
.directive("toast", function(){
return{
restrict: "A",
scope: {
param: "="
},
link: function(scope){
console.log(scope.param)
}
}
})
Run Code Online (Sandbox Code Playgroud)
我肯定会收到错误 Multiple directives [alert, toast] asking for new/isolated scope on:<div...
总而言之,我的问题是,如何在没有隔离范围的情况下重命名父范围变量,以及如何在两个directives放置在单个范围内时共享变量DOM?
Pat*_*ick 14
修改吐司指令:
.directive("toast", function(){
return{
restrict: "A",
link: function(scope, elem, attrs){
var param = scope.$eval(attrs.param);
console.log(param)
}
}
})
Run Code Online (Sandbox Code Playgroud)
由于toast现在与父级所在的范围相同(如果允许它是隔离范围),您只需使用param属性调用范围上的$ eval即可获取值.
| 归档时间: |
|
| 查看次数: |
8723 次 |
| 最近记录: |