【问题标题】:Access controller from a directive within a directive that has isolated scope从具有隔离范围的指令中的指令访问控制器
【发布时间】:2013-02-21 14:14:25
【问题描述】:

我刚刚开始使用 angularJS,但在使用指令和控制器进行范围界定时遇到了一些问题。

在下面链接的示例中,我有一组两个指令;一个属性指令 (showMessage) 和一个元素指令 (parentDirective)。

http://jsfiddle.net/ejSxM/1/

我想使用showMessage 作为一种行为,这样当一个元素被点击时,它会在控制器中触发一个函数。这适用于普通的 html 元素,但是当我将它应用到我的parentDirective 时,showMessage 会占用parentDirective 的范围,而不是控制器。

这可以在随附的示例中进行演示。当点击“我一个人”时,指令具有控制器的作用域,因此控制器作用域中的showMessage 函数调用正常。但是,当单击“我是指令”时,该指令现在具有父指令的范围,并标记错误。

有没有一种方法可以让我从嵌套指令访问控制器作用域,即使父指令具有隔离作用域?

【问题讨论】:

    标签: javascript controller angularjs directive


    【解决方案1】:

    您可以像这样将表达式传递给您的指令: <my-directive onsomeevent="functionInMyController()"></my-directive>

    然后在你的指令中:

    ...
    scope: {
        onevent: '&onsomeevent'
    },
    link: function() {
        element.bind('click',function () {
           scope.onevent(); 
        });
    }
    ...
    

    也就是说,您从 onsomeevent 参数绑定表达式,这样您就可以在指令中执行它,而无需知道表达式是什么。表达式在父作用域上执行,所以需要在父作用域中定义functionInMyController。您还可以将链接函数中的变量传递给该表达式,您可以在此处(在范围部分)directives 找到一个示例。

    【讨论】:

    • 感谢您的帮助。这种不同的方法完全符合我的需求,我可以取消现在不必要的行为指令。如果有人有兴趣,这里是另一个使用上述方法的 jsfiddle:jsfiddle.net/HDEF7/3
    【解决方案2】:

    您可以为指令设置控制器。

    controller - Controller constructor function. The controller is instantiated 
    before the pre-linking phase and it is shared with other directives if they 
    request it by name (see require attribute).
    This allows the directives to communicate with each other and augment each other's 
    behavior. The controller is injectable with the following locals:
    $scope - Current scope associated with the element
    $element - Current element
    $attrs - Current attributes obeject for the element
    $transclude - A transclude linking function pre-bound to the correct transclusion
    scope:     
    function(cloneLinkingFn).
    

    http://docs.angularjs.org/guide/directive

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多