0

我正在使用 Angular 1.5 构建一个简单的网格组件component。结构是:

<grid-component>
    <grid-header>
        <grid-cell key="one">Column One</grid-cell>
        <grid-cell key="two">Column Two</grid-cell>
        <grid-cell key="three">Column Three</grid-cell>
    </grid-header>
    <grid-row ng-repeat="item in ctrl.items" model="items">
        <grid-cell key="one">{{ items.one }}</grid-cell>
        <grid-cell key="two">{{ items.two }}</grid-cell>
        <grid-cell key="three">{{ items.three }}</grid-cell>
    </grid-row>
</grid-component>

<grid-component>广播事件<grid-header>,但标头组件未接收到消息。

这是我使用的一个简单示例。

app
.component('gridComponent', {
    controller: function($scope) {
        this.$onInit = function() {
            resource.getItems()
                .then(function(items) {
                    $scope.broadcast('update', items);
                }); 
        };
    }
})
.component('gridHeader', {
    controller: function($scope) {
        $scope.on('update', function(event, items) {
            controller.items = items;
        });
    }
});

有趣的是,当我检查作用域时,它们实际上是作用域层次结构中的兄弟。

家长

{
    childHead: null,
    $$childTail: null,
    $$destroyed: false,
    $$isolateBindings: Object,
    $$listenerCount: Object,
    $$listeners: Object,
    $$nextSibling: null,
    $$phase: null,
    $$prevSibling: null,
    $$watchers: null,
    $$watchersCount: 0,
    $ctrl:module.exports.controller,
    $id: 80,
    $parent: {
        $$ChildScope: null,
        $$childHead: h,
        $$childTail: h,
        $$listenerCount: Object,
        $$listeners: Object,
        $$nextSibling: null,
        $$prevSibling: null,
        $$transcluded: true,
        $$watchers: Array[4],
        $$watchersCount: 4,
        $id: 79,    <---
        $parent: {}
    }
}

孩子

{
    childHead: null,
    $$childTail: null,
    $$destroyed: false,
    $$isolateBindings: Object,
    $$listenerCount: Object,
    $$listeners: Object,
    $$nextSibling: null,
    $$phase: null,
    $$prevSibling: { parentObject }, <---
    $$watchers: null,
    $$watchersCount: 0,
    $ctrl:module.exports.controller,
    $id: 91,
    $parent: {
        $$ChildScope: null,
        $$childHead: h,
        $$childTail: h,
        $$listenerCount: Object,
        $$listeners: Object,
        $$nextSibling: null,
        $$prevSibling: null,
        $$transcluded: true,
        $$watchers: Array[4],
        $$watchersCount: 4,
        $id: 79, <---
        $parent: {}
    }
}

两者的父母的注意 id 是相同的。另外,请注意,孩子的 prevSibling 是父母。

如果我更改$scope.$broadcast$scope.$parent.$broadcast它按预期工作,因为他们是兄弟姐妹。

当它们是嵌套组件时,为什么 Angular 将它们视为兄弟姐妹,并且有没有一种无需遍历$parent链即可广播事件的方法?

4

0 回答 0