2013-02-21 82 views
2

我刚刚开始与angularJS,我有一个问题让我的头围绕指令和控制器的范围。访问控制器从一个指令中的指令,有一个孤立的范围

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

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

我想使用showMessage作为行为,以便被点击的元素时,它触发一个控制器中的功能。这在正常的html元素上工作正常,但是当我将它应用于我的parentDirective,showMessage时,其范围为parentDirective,而不是控制器。

这可以在附件中演示。当点击“我是我自己”时,该指令具有控制器的范围,因此控制器作用域中的showMessage函数调用正常。然而,当单击“我是指令”时,指令现在具有父指令的范围,并标记出错。

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

回答

4

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

,然后在指令:

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

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

+0

感谢您的帮助。这种不同的方法完全符合我的需求,并且我可以取消现在不必要的行为指令。如果有人感兴趣,这里是另一个使用上述方法的jsfiddle:http://jsfiddle.net/HDEF7/3/ – Sam 2013-02-21 15:25:25

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

相关问题