【发布时间】:2014-12-30 17:29:14
【问题描述】:
我正在学习 AngularJS 指令,我想做的一件事是在父 scope(scope 的 controller)中传递一些变量 $scope.message,我希望它重命名为param 在 directive alert 内。我可以用一个孤立的范围来做到这一点:
<div alert param="message"></div>
并定义
.directive("alert", function(){
return{
restrict: "A",
scope: {
param: "="
},
link: function(scope){
console.log(scope.param) # log the message correctly
}
}
})
但是我可以在不使用隔离作用域的情况下做到这一点吗?假设我想在<div toast alert></div> 中添加另一个directive toast 并使用相同的param(保持2 路数据绑定),我会天真地这样做
.directive("toast", function(){
return{
restrict: "A",
scope: {
param: "="
},
link: function(scope){
console.log(scope.param)
}
}
})
我肯定会收到错误Multiple directives [alert, toast] asking for new/isolated scope on:<div...
所以总的来说,我的问题是,如何在没有隔离范围的情况下重命名父范围变量,以及当两个 directives 放在一个 DOM 上时如何共享变量?
【问题讨论】:
-
你想让 2 个指令绑定到同一个父
$scope属性吗?
标签: angularjs angularjs-directive angularjs-scope