Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why 'continue' doesn't work within an angular foreach?

Tags:

angularjs

I have an angular app as the following and I have a angular.forEach function where I want to skip some values with the continue keyword but I can't.

<div ng-app="app">
  <div ng-controller="test">
    test
    {{printPairs()}}
  </div>
</div>

angular.module("app", [])
       .controller("test", function($scope){
          var array = [1,2,3,4,5,6];

          $scope.printPairs = function(){
            angular.forEach(array, function (elem) {
              if(elem % 2 === 1){
                 continue;
              }
              //More logic  below...
            })
          };
       });

Someone knows why is this happening?

like image 854
raven Avatar asked Nov 30 '16 21:11

raven


1 Answers

This happens because you are not inside a javascript foreach statement.

But we are in a function. How you can see angular.forEach second parameter is a callback witch is called in every loop.

So to solve your problem you can just use a simple "return" to jump the current position who match with your if condition, like this:

angular.forEach(array, function (value, key) {
     if(1 === value % 2){
        return;
     }
     //More logic  below...
 })
like image 137
Felipe Lima Alcântara Avatar answered Sep 27 '22 02:09

Felipe Lima Alcântara