簡體   English   中英

具有隔離范圍的指令中的指令中的訪問控制器

[英]Access controller from a directive within a directive that has isolated scope

我剛開始使用angularJS,但在使用指令和控制器進行范圍界定時遇到了一個問題。

在下面鏈接到的示例中,我有一組兩個指令。 一個屬性指令( showMessage )和一個元素指令( parentDirective )。

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

我想將showMessage用作行為,以便在單擊某個元素時會觸發控制器中的一個函數。 這工作正常,正常的HTML元素,但是當我把它應用到我的parentDirectiveshowMessage取的范圍parentDirective ,而不是控制。

這可以在所附示例中進行演示。 當單擊“我一個人showMessage ”時,該指令具有控制器的作用域,因此控制器作用域中的showMessage函數調用正常。 但是,當單擊“我是指令”時,該指令現在具有父指令的范圍,並標記一個錯誤。

有什么方法可以使我從嵌套指令訪問控制器范圍,即使父指令具有隔離范圍也是如此?

您可以像這樣將表達式傳遞到您的指令: <my-directive onsomeevent="functionInMyController()"></my-directive>

然后在您的指令中:

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

也就是說,您可以通過onsomeevent參數綁定表達式,以便可以在指令內部執行它而無需知道表達式是什么。 該表達式在父范圍內執行,因此functionInMyController需要在父范圍內定義。 您還可以將變量從鏈接函數傳遞到該表達式,您可以在此處(作用域部分)找到指令的示例。

您可以為指令設置控制器。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM