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;
  }
})
有帮助吗?

解决方案

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.

其他提示

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.

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top