AngularJS 1.5组件在更改时不会调用$ onChanges

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

我在html页面中有一个AngularJS 1.5组件(不是父组件)并且该组件不会在更改时调用$ onChanges。

HTML

<my-comp standards-data="standardsData"></my-comp>

Component

angular.module("bla").component('myComp', {
    templateUrl: '/my-comp.tpl.html',
    controller: myController,
    bindings: {
        standardsData: '<'
    }
});

function myController() {
    var self = this;

    self.$onInit = function () {
        self.standardsData = {};
    }

    self.$onChanges = function (changes) {
        self.standardsData.something = changes.standardsData.currentValue.something;
    };
}

[当我在包含我的组件的html的ctrl中获取新数据时,它不会影响组件。我只进入组件的$onInit$scope.standardsData更改后(包含html / ctrl),我组件的$OnChanges将不会调用。

希望我正确地描述了这个问题,谢谢!

javascript html angularjs components angularjs-components
1个回答
4
投票

您绑定到standardsData的组件是对对象引用的绑定,即使修改了其属性之一,该引用也不会更改。结果,不会触发$onChanges。这是由于$onChanges使用浅$watch

换句话说,仅当我们使用基元(即非对象)或更改绑定到组件中的javascript对象的reference时,才会触发$onChanges

因此,您需要执行以下操作之一:1)手动绑定到所需的一个或多个属性,而不是对象引用,或者2)当其数据更改时更改整个standardsData对象。 您也可以3)重写$onChanges功能,我想(不推荐)

选项1:仅绑定到属性

如果父控制器/组件仅更改一个或多个属性,则使用。

<my-comp standards-data-something="standardsData.something"></my-comp>

bindings: {
    standardsDataSomething: '<'
}

选项2:更改参考

[如果父控制器/组件获得全新的standardsData,则使用。您将为此选项保留当前HTML并设置:

standardsData = {newData};  //Reset the new data from http or wherever

更改参考。


一些进一步的阅读,您可能会发现很有趣:

http://blog.kwintenp.com/the-onchanges-lifecycle-hook/

http://www.codelord.net/2016/12/20/replacing-angulars-deep-watches-with-the-%24docheck-lifecycle-hook/

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