【问题标题】:Pass variable to AngularJS directive without isolated scope在没有隔离范围的情况下将变量传递给 AngularJS 指令
【发布时间】: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
        }
    }
})

但是我可以在不使用隔离作用域的情况下做到这一点吗?假设我想在&lt;div toast alert&gt;&lt;/div&gt; 中添加另一个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:&lt;div...

所以总的来说,我的问题是,如何在没有隔离范围的情况下重命名父范围变量,以及当两个 directives 放在一个 DOM 上时如何共享变量?

【问题讨论】:

  • 你想让 2 个指令绑定到同一个父 $scope 属性吗?

标签: angularjs angularjs-directive angularjs-scope


【解决方案1】:

修改你的 toast 指令:

.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 来获取值。

【讨论】:

  • 谢谢,完美运行!那我应该看看$eval() docs。
  • $eval() 只是返回值还是实际提供数据绑定?它似乎只返回值,但我想确定一下。
  • 这只是价值。如果您需要模拟绑定,您可以使用 $watch... 我相信这可能有点过头了,因为您只需再次 $eval 即可获得最新的值(例如在某些 ngEvent 上)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多