0

如果您有一个指令在一个页面上多次使用,那么一个指令如何与另一个指令通信?

我试图在父子关系中将指令链接在一起。单击指令 A 时,我想过滤指令 B 以仅在指令 A 中包含所选项目的子项。在这种情况下,页面上可能有无限数量的指令和关系。

通常我会让指令 A 对它的每个子级调用一个过滤器方法,每个子级调用它的子级以继续向下过滤层次结构。

但我不知道是否可以从 1 个指令调用方法到另一个指令。

谢谢

4

2 回答 2

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

另一个可能适用于您需要的选项是拥有一个服务,每个指令都会设置一个监视并可以操作。例如,directive1 可以监视服务中的属性并响应更改,并设置一个可以更改该属性的按钮。然后,directive2 也可以监视和更改服务,无论您如何设置,它们都会相互响应。如果你也需要一个 jsbin,请告诉我。

我希望这有帮助!

于 2013-08-20T06:46:18.870 回答
0

您可以尝试将所有数据放入指令可以引用的服务中。

就像是:

app.factory('selectedStuffService', function(){
    var allItems = [];
    var selectedItems = [];

    function addSelectedItem(item){
         selectedItems.push(item);
    }

    return {
        allItems: allItems,
        selectedItems: selectedItems,
        addSelectedItem: addSelectedItem
    }
}

指令 A 中的交互更改 selectedItems 数组中的值,指令 B 可以绑定到它。您可以轻松地向服务添加其他方法以根据需要过滤/操作项目,并且使用该服务的任何指令都应该能够根据其他指令所做的更改进行更新。

于 2013-08-20T14:15:50.620 回答