组件不会从父angularjs接收更新

问题描述 投票:0回答:1

我正在尝试从父组件(异步更新)接收更新,但是当原始$ onInit从父组件接收数据时,任何更新都不会更新父组件(返回为未定义)

有什么方法可以接收更新?

子组件:

import template from 'html-loader!./child.html'

export const childComponent = {
    template: template,
    require: {
        parentComponent: '^parentComponent'
    },
    controllerAs: 'vm',
    controller: class {

        constructor($scope) {
            this.option = null
            this.items = []
            this.$scope = $scope
        }

        static get $inject() {
            return ['$scope']
        }

        $onInit() {
            this.items = this.parentComponent.items
            // this.items doesn't get updated when this.parentComponent updates
        }
    }
}

更新:

<div ng-app="app">

    <div ng-controller="AppController as vm">
        <parent-component items="vm.fruit">
            <div ng-if="vm.fruit.length < 1">Loading...</div>
            <child-component></child-component>
        </parent-component>
    </div>

</div>
angularjs components
1个回答
1
投票

Take a look at this demo

原因,$onInit()没有被调用因为,你需要你需要添加两件事:

transclude: true声明中添加parentComponent

然后在html中添加ng-transclude如下:

<parent-component ng-transclude>

  <child-component></child-component>

</parent-component>

© www.soinside.com 2019 - 2024. All rights reserved.