1

Is there anyway to force angular to update/recompile the variables within a binding? I'm having an issue when I set my array (which is defined as a for loop within my HTML) equal to [] and it doesn't pick up on it. Any ideas?

matsko
  • 21,895
  • 21
  • 102
  • 144
  • 1
    angular triggers DOM updates in digest cycles so you could try to call Scope.$digest() - see for more. Having said this, directly calling $digest is usually very bad idea so I guess that we are missing something in your app design. Could you please send a jsFiddle better illustrating your use case? – pkozlowski.opensource Aug 08 '12 at 18:01
  • Could you provide a jsfiddle demonstrating issue. That would help a lot. – Dan Doyon Aug 08 '12 at 18:01
  • 1
    If you are using an external library/plugin, Scope.$digest() could be your answer but if this is not the case then I wouldn't go there -- yet. – Dan Doyon Aug 08 '12 at 18:03
  • 1
    Perfect. $scope.$digest worked perfectly! – matsko Aug 08 '12 at 19:28

1 Answers1

3

One workaround is to make sure you work with the same array reference. I've been doing it like this whenever I want to update all of the elements to a bound array:

myArray.length = 0;
angular.forEach(newArray, function(item){
   myArray.push(item);
})

// Note: try without this line first as it isn't always necessary
$scope.$digest();

Using myArray.length = 0 clears out the array retaining the reference to the array see this post for more info.

You can also use the usual splice and unshift to remove and add items to the beginning of the array respectively.

Community
  • 1
  • 1
Gloopy
  • 37,767
  • 15
  • 103
  • 71
  • Your answer is almost correct. Can you please just add "$scope.$digest();" as the last line and then I set your answer as accepted. – matsko Aug 08 '12 at 19:27
  • I've added the code with a disclaimer only because I've never had to use it (at least with an ng-repeat). Good to know guys in case I am having binding issues in the future! – Gloopy Aug 08 '12 at 20:17