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;
  }
})
3
  • just return or break Commented May 13, 2014 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 Commented May 13, 2014 at 13:22
  • 1
    There is no simple way to break from an angular.foreach and the reason why is explained here. You can try something like what is explained in the top answer of How to short circuit Array.forEach like calling break? Commented May 13, 2014 at 13:27

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I used a regular for (var key in $scope.obj){} and was able to break on the if statement.
That's it! Solved... :)
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.

2 Comments

Array.prototype.some would work as well.
Yes, more or less one is the opposite of the other: one works while true is returned, the other while false
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.

2 Comments

angular.forEach is not async
Woops, it is not indeed. But there is no break'ing in anulars implementation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.