从具有隔离范围的指令中的指令访问控制器

时间:2013-02-21 14:14:25

标签: javascript controller angularjs directive

我刚刚开始使用angularJS,而且我在使用指令和控制器时遇到了一些问题。

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

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

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

这可以在附加的例子中说明。当单击“我自己”时,该指令具有控制器的范围,因此控制器范围中的showMessage函数调用正常。但是,当单击“我是一个指令”时,该指令现在具有父指令的范围,并标记错误。

有没有办法可以从嵌套指令访问控制器作用域,即使父指令有一个隔离的作用域?

2 个答案:

答案 0 :(得分:4)

您可以将表达式传递给您的指令,如下所示: <my-directive onsomeevent="functionInMyController()"></my-directive>

然后在你的指令中:

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

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

答案 1 :(得分:1)

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

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