angularjs 指令之间的通信

Communication between angularjs directives

我有一个 'master',它使用 templateUrl 来指定它应该使用的标记。在该模板中,我使用 'rows' 指令在视图中布局 div。因此,'master' 指令是 'rows' 的一种父指令。

'rows' 指令也使用 templateUrl。 'master' 和 'rows' 指令在许多情况下被重复使用,但我需要让 'rows' 指令在每一行中以不同的方式布局其行。这会阻止我在 'rows' 指令上使用属性,因为这会产生全局影响。

我想在 'master' 指令上添加属性,并以某种方式将这些属性传递给 'rows' 指令。

有什么方法可以做到这一点吗?我看过一个关于指令间通信的 EggHead 教程,但是它使用 'child' 指令作为 'parent' 上的一个属性,这对我不起作用。

我还了解到我可以使用服务在两者之间进行通信,但我不清楚如何进行。 Angular 的 $broadcast 可能有效,但考虑到行数,可能会有很多行,如果不是连续完成,我的布局可能会受到影响。

有些人会争辩说您应该使用事件,但我认为在您的情况下指令级控制器来存储数据会更好。由于您的 row 指令依赖于您的 master 指令,您可以利用它来发挥自己的优势并将共享信息存储在 master指令。

module.directive('masterDir', function() {
    return {
        // Requiring yourself makes 
        //   the directive level controller
        //   available in the link function
        require: 'masterDir',
        controller: function($scope) {
            // The return is needed to support Angular 1.2
            return this;
        },
        link: {
            pre: function(scope, element, attrs, masterDirCtrl) {
                masterDirCrtl.someAttribute = attrs.someAttributeFromTheDom;
            },
            post: function() {
            }
        }
    }
});


module.directive('rowDir', function() {
    return {
        require: 'masterDir',
        link: function(scope, element, attrs, masterDirCtrl) {
            var parentDirectiveAttr = masterDirCrtl.someAttribute;
        }
    }
});