Angular 组件绑定对象未初始化

Angular component bindings objects not initialised

我在我的项目中使用 angular 1.5 组件。在我的组件中,对象数据总是未定义。

我希望 $ctrl.products 在调用产品结果组件之前没有被初始化。 product-result组件初始化后如何调用
$ctrl.products 个对象。

products.list.component.html

<div class="container">
    <div class="col-md-6" >
        <span>{{$ctrl.products}}</span>
        <product-result data="$ctrl.results" max="6"></product-result>
    </div>

</div>

如果你想在$ctrl.products初始化后初始化组件,那么你可以使用angular提供的$compile服务。

在初始化 $ctrl.products 的行之后使用下面的行:

var domObj = $compile('<my-directive></my-directive>')($scope);
$('selector where you want to append this directive').append(domObj);

实现此目的的一种方法是挂接到 angular 的新组件方法,即 $onChanges$onInit

如果 products.list.component.js 确实对产品对象调用 API,然后呈现新的 $ctrl.results 数据集。

您可以让 product-result.js 组件使用新的 $onChanges 方法检查 $ctrl.results 的单向绑定。每当更新单向绑定时调用 $onChanges。该方法接受一个更改对象参数。 changes 对象的键是已更改的绑定属性的名称。

您的 product-result.js 代码可以是

/**
 * @ngdoc function
 * @name $onInit
 * @description on bootstrap for the component check if the value `ctrl.results ` is falsy    
*/
$onInit: function $onInit () {
    if (!this.results) {
        this.showNoDataAvaliable = true;
    }
},

/**
 * @ngdoc function
 * @name $onChanges
 * @description when component product-list passes a new value for $ctrl.results,  Show the data.
 * @param {Object} changes the changes object when any binding property is updated, this is similar to
 * having a watch function on $scope.variable   
 */
$onChanges: function $onChanges (changes) {
    if (changes.data && changes.data.currentValue) {
        this.showNoDataAvaliable = false;
        //... more code on how to display the data.
    }
}

Todd Motto 有一篇很棒的博客 post 关于 angular 1.5 组件,我建议您阅读 https://toddmotto.com/angular-1-5-lifecycle-hooks

一个更简单的解决方案是使用 ng-if 延迟内部组件的渲染,直到加载结果:

<product-result ng-if="$ctrl.results" data="$ctrl.results" max="6"></product-result>

这将允许您将 HTML 保留在它所属的模板中,但会阻止内部组件添加到 DOM 并在定义 $ctrl.results 之前进行初始化。