0

I have an if statement but need it to "break" if the first condition is met but AFTER I have completed some processes. The if statement is wrapped inside a forEach statement in Angular.

angular.forEach($scope.obj, function ( value, key) {
  if( id == key) {
    delete $scope.obj[id];
    result.clicked = false;
    //break here, don't run the else
  } else {
    $scope.obj[id] = result;
    result.clicked = true;
  }
})
user1876246
  • 1,219
  • 5
  • 18
  • 33
  • just `return` or `break` – abc123 May 13 '14 at 13:21
  • where would I put them? can you be more specific? I tried return where the comment is but that did nothing because the loop kept running – user1876246 May 13 '14 at 13:22
  • 1
    There is no simple way to break from an `angular.foreach` and the reason why is explained [here](https://github.com/angular/angular.js/issues/263). You can try something like what is explained in the top answer of [How to short circuit Array.forEach like calling break?](http://stackoverflow.com/questions/2641347/how-to-short-circuit-array-foreach-like-calling-break) – Marc Kline May 13 '14 at 13:27

3 Answers3

1

Angular documentation says nothing about stopping forEach, it seems it cannot be stopped. Maybe you should use something like Array.prototype.every. On the other hand, maybe you can stop it throwing an error... but it seems a dirty way to do it.

Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59
  • 1
    [Array.prototype.some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) would work as well. – Marc Kline May 13 '14 at 13:35
  • Yes, more or less one is the opposite of the other: one works while true is returned, the other while false – Pablo Lozano May 13 '14 at 13:36
1

There's no way to do this, Angular forEach loop can't break on condition match. Use native FOR loop instead of angular.forEach, Because for will allow you to break in between.

Dhaval Marthak
  • 17,246
  • 6
  • 46
  • 68
0

Since Angular.forEach is async, you can not break, because there is no loop. If you use a normal loop, you can break as usual.

Spiked
  • 11