2

我在我的项目中使用 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>
4

3 回答 3

2

实现这一点的一种方法是挂钩到 Angular 的新组件方法,即$onChanges$onInit.

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

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

你的代码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 有一篇关于 Angular 1.5 组件的精彩博客文章,我建议您阅读 https://toddmotto.com/angular-1-5-lifecycle-hooks

于 2016-06-26T13:09:33.193 回答
1

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

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

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

于 2016-07-06T23:52:04.090 回答
-1

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

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

var domObj = $compile('<my-directive></my-directive>')($scope);
$('selector where you want to append this directive').append(domObj);
于 2016-06-25T17:44:25.077 回答