AngularJS not refreshing ngRepeat when updating array
angularjs, angularjs-ng-repeat, javascript
Solution
You are modifying the scope outside of angular's `$digest` cycle 50% of the time.
If there is a callback which is not from angularjs; (posibbly jquery). You need to call `$apply` to force a `$digest` cycle. But you cannot call `$apply` while in `$digest` cycle because every change you made will be reflected automatically already.
You need to know when the callback is not from angular and should call `$apply` only then.
If you don't know and not able to learn, here is a neat trick:
var applyFn = function () {
$scope.someProp = "123";
};
if ($scope.$$phase) { // most of the time it is "$digest"
applyFn();
} else {
$scope.$apply(applyFn);
}
Problem
I'm having serious troubles understanding AngularJS sometimes. So I have a basic array in my controller like ``` $scope.items = ["a","b","c"] ``` I'm ngRepeating in my template over the items array ng-repeat="item in items". Super straightfoward so far. After a couple of UX actions, I want to push some new stuff to my array. ``` $scope.items.push("something"); ``` So, 50% of the time, the new element is added to the view. But the other 50%, nothing happens. And it's like super frustrating; bc if I wrap that within $scope.$apply(), I got a "$digest already in progress" error. Wrapping that into $timeout doesn't help either. And when I inspect my element scope using the Chrome extension; I can see the new data is there and the $scope.items value is correct. But the view is just not taking care of adding that to the DOM. Thanks!