在执行链接函数之前,在父指令中获取子指令的数量

Vin*_*ent 8 javascript angularjs angularjs-directive

当使用一个指令和多个子指令(使用require)时,有什么方法可以知道将执行多少个子指令?

我可以在每次执行子指令时计算(在链接函数中).但我希望父指令知道在执行子指令的最后一个链接函数之前有多少个子节点.

我需要知道,因为当最后一个元素从子节点传递给父指令时,我需要一些特定的行为.

hon*_*n2a 3

您可以利用链接分两个阶段完成的事实。您可以首先在“链接前阶段”注册所有子级,然后在“链接后阶段”,您就可以访问所需的信息。

.directive('parent', function () {
    return {
        controller: function () {
            this.childCount = {
                pre: 0,
                post: 0
            };
        },
        link: function () {}
    };
})
.directive('child', function () {
    return {
        require: '^parent',
        compile: function () {
            return {
                pre: function ($scope, $element, $attrs, parentCtrl) {
                    ++parentCtrl.childCount.pre;
                },
                post: function ($scope, $element, $attrs, parentCtrl) {
                    ++parentCtrl.childCount.post;
                    if (parentCtrl.childCount.post === parentCtrl.childCount.pre) {
                        // ... (this runs only on the last linked child)
                    }
                }
            };
        }
    };
})
Run Code Online (Sandbox Code Playgroud)

这样您就可以在最后一个子链接期间访问该信息。

当然,如果您不需要那么快的信息,您可以在父控制器中注册所有子控制器,然后从父链接后函数运行最后注册的子控制器的方法。