2

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

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

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

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

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

有没有一种方法可以从嵌套指令访问控制器范围,即使父指令具有隔离范围?

4

2 回答 2

4

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

然后在你的指令中:

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

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

于 2013-02-21T14:22:51.637 回答
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

于 2013-02-21T14:51:10.883 回答