子组件未从父母接收广播

时间:2016-10-06 18:33:56

标签: javascript angularjs angular-components angular-broadcast

我正在使用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链的情况下广播事件?

0 个答案:

没有答案