What is the reason behind Angular's failure to detect changes in an array, but successfully does so after changing it to null first?
In my AngularJS component, I utilize a two-way data binding to pass an array. The parent component contains a button with an ng-click event that calls this function:
onClickAddValue()
{
this.listOfValues.push(this.valueInput);
}
The value of this.listOfValues
remains unchanged even after adding a new value to the array, resulting in no updates to the child component's view. Understanding this behavior, I attempted to overcome it by resetting the array as shown below:
onClickAddValue()
{
var oldList = this.listOfValues;
this.listOfValues = [];
for (let value of oldList)
{
this.listOfValues.push(value);
}
this.listOfValues.push(this.valueInput);
}
However, this approach did not yield the desired outcome. I also experimented with Object.assign
and angular.copy
, but to no avail. Interestingly, the following code snippet proves effective:
onClickAddValue()
{
var oldList = this.listOfValues;
this.listOfValues = null;
setTimeout(
() =>
{
this.listOfValues = oldList;
this.listOfValues.push(this.valueInput);
this.$scope.$digest();
}
);
}
This implementation works because setting listOfValues
to null triggers a digest cycle, prompting Angular to recognize the change and update the view. Subsequently, updating the array again within the same context ensures another digest cycle and subsequent view update. On the contrary, why doesn't the initial approach work? What makes altering the object differ from resetting it to null first, followed by making modifications?