gpt4 book ai didi

javascript - 将新对象传递给 Angular 绑定(bind)时出现无限摘要错误

转载 作者:行者123 更新时间:2023-11-30 21:13:26 25 4
gpt4 key购买 nike

我正在尝试通过单向绑定(bind)变量将一组计数作为对象传递,并得到无限摘要,因为我绑定(bind)到组件的方法每次都返回一个新对象。这是示例:

在父组件模板中:

<some-component counts="$ctrl.selectedCounts()"></some-component>

父组件定义:

angular.module().component('parentComponent', {
controller() {
return {
selectedCounts() {
return {
[this.selectedThing1.length > 1 ? 'thing' : 'things']: this.selectedThing1.length,
[this.selectedThing2.length > 1 ? 'thing' : 'things']: this.selectedThing2.length,
}
}
}
}
})

如何绑定(bind)此 counts 绑定(bind),使其在不改变父组件中的对象并将其传递给 some-component 的情况下不创建无限摘要?我尝试使用 =* 作为 some-component 中的绑定(bind),虽然它不会创建无限的摘要循环,但它也不会将更改传播到然后出于某种原因子组件。

这是一个具有相同无限摘要的 fiddle : http://jsfiddle.net/joshdmiller/HB7LU/

最佳答案

With object content — 使用$doCheck 生命周期钩子(Hook) 1

绑定(bind)对象或数组引用时,$onChanges Hook 仅在引用的 发生变化时执行。要检查对对象或数组的内容 的更改,请使用$doCheck 生命周期 Hook :

app.component('nvPersonalTodo', {
bindings: {
todos: "<"
},
controller: function(){
var vm = this;
this.$doCheck = function () {
var oldTodos;
if (!angular.equals(oldTodos, vm.todos)) {
oldTodos = angular.copy(vm.todos);
console.log("new content");
//more code here
};
}
})

来自文档:

The controller can provide the following methods that act as life-cycle hooks:

  • $doCheck() - Called on each turn of the digest cycle. Provides an opportunity to detect and act on changes. Any actions that you wish to take in response to the changes that you detect must be invoked from this hook; implementing this has no effect on when $onChanges is called. For example, this hook could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not be detected by Angular's change detector and thus not trigger $onChanges. This hook is invoked with no arguments; if detecting changes, you must store the previous value(s) for comparison to the current values.

— AngularJS Comprehensive Directive API Reference -- Life-cycle hooks

更多信息,

关于javascript - 将新对象传递给 Angular 绑定(bind)时出现无限摘要错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45910811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com