如果一个指令在一个页面上被多次使用,那么一个指令如何与另一个指令通信呢?
我试图在父子关系中将指令链接在一起。当单击指令A时,我希望过滤指令B,使其仅包含指令A中所选项目的子项。在这种情况下,页面上可能有无限数量的指令和关系。
通常,我会让指令A在它的每个子级上调用一个filter方法,每个子级都调用它的子级来继续向下过滤层次结构。
但是我不知道从一个指令到另一个指令调用方法是否可行。
谢谢
发布于 2013-08-20 14:46:19
听起来你正在寻找一个指令控制器。您可以使用指令的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();
}
};
});在angular文档中,这里有一些你可以使用的符号和它们的用途。
(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
另一个可能适用于您所需的选项是拥有一个服务,每个指令在该服务上设置一个监视并可以对其进行操作。例如,directive1可以监视服务中的属性并响应更改,还可以设置一个可以更改该属性的按钮。然后,directive2还可以监视和更改服务,无论您如何设置,它们都会相互响应。如果你也需要一个jsbin,请告诉我。
我希望这能帮到你!
发布于 2013-08-20 22:15:51
您可以尝试将所有数据放入每个指令都可以引用的服务中。
类似于:
app.factory('selectedStuffService', function(){
var allItems = [];
var selectedItems = [];
function addSelectedItem(item){
selectedItems.push(item);
}
return {
allItems: allItems,
selectedItems: selectedItems,
addSelectedItem: addSelectedItem
}
}指令A中的交互改变了selectedItems数组中的值,而指令B可以绑定到它。您可以轻松地将其他方法添加到服务中,以便根据需要过滤/操作项目,并且使用该服务的任何指令都应该能够根据其他指令所做的更改进行更新。
https://stackoverflow.com/questions/18324910
复制相似问题