将变量传递给AngularJS指令而不使用隔离范围

时间:2014-12-30 17:29:15

标签: angularjs angularjs-directive angularjs-scope

我正在学习AngularJS指令,我想要做的一件事就是在父$scope.messagescope的{​​{1}})中传递一些变量scope,我希望它在controller 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 } } }) 添加另一个directive toast并使用相同的<div toast alert></div>(保持双向数据绑定),天真地我会做

param

我肯定会收到错误.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上时如何共享变量?

1 个答案:

答案 0 :(得分:14)

修改吐司指令:

.directive("toast", function(){
    return{
        restrict: "A",
        link: function(scope, elem, attrs){
            var param = scope.$eval(attrs.param);
            console.log(param)
        }
    }
})

Example fiddle

由于toast现在与父级所在的范围相同(如果允许它是隔离范围),您只需使用param属性调用范围内的$ eval即可获得该值。

相关问题