[英]Angular Directive to Directive call
如果您有一個指令要在頁面上多次使用,那么1個指令如何與另一個指令進行通信?
我正在嘗試在父子關系中將指令鏈接在一起。 單擊指令A時,我希望過濾指令B,使其僅在指令A中具有所選項目的子項。在這種情況下,頁面上可能有無限數量的指令和關系。
通常,我會在指令A的每個子級上調用filter方法,並且每個子級都調用其子級來繼續過濾層次結構。
但是我不知道從1指令到另一個指令的調用方法是否是可能的。
謝謝
聽起來您正在尋找指令控制器。 您可以使用指令的require:
參數引入另一個指令的控制器。 看起來像這樣:
app.directive('foo', function() {
return {
restrict: 'A',
controller: function() {
this.qux = function() {
console.log("I'm from foo!");
};
},
link: function(scope, element, attrs) {
}
};
});
app.directive('bar', function() {
return {
restrict: 'A',
require: '^foo',
link: function(scope, element, attrs, foo) {
foo.qux();
}
};
});
在有角度的文檔中,這是可以與require一起使用的符號以及它們的作用。
(no prefix) - Locate the required controller on the current element.
? - Attempt to locate the required controller, or return null if not found.
^ - Locate the required controller by searching the element's parents.
?^ - Attempt to locate the required controller by searching the element's parents, or return null if not found.
這是我的示例的jsbin。 http://jsbin.com/aLikEF/1/edit
另一種可能滿足您需要的選項是提供一個服務,每個指令都可以設置監視並可以操縱。 例如,指令1可以監視服務中的屬性並響應更改,還可以設置可以更改該屬性的按鈕。 然后,偽指令2也可以監視和更改服務,並且無論您是否進行了設置,它們都會相互響應。 如果您還需要一個jsbin,請告訴我。
我希望這有幫助!
您可以嘗試將所有數據放入指令可以分別引用的服務中。
就像是:
app.factory('selectedStuffService', function(){
var allItems = [];
var selectedItems = [];
function addSelectedItem(item){
selectedItems.push(item);
}
return {
allItems: allItems,
selectedItems: selectedItems,
addSelectedItem: addSelectedItem
}
}
指令A中的交互更改了selectedItems數組中的值,指令B可以綁定到它。 您可以輕松地向服務中添加其他方法,以根據需要過濾/操作項目,並且使用該服務的任何指令都應能夠根據其他指令所做的更改進行更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.