2

angular forEach not working with ng-if function but working using simple if Please check fiddle

https://jsfiddle.net/hzdyhx4n/

angular.module('app5', []).controller('ctrl', function($scope) {
$scope.z = [ { name: 'aa', id: 55, picture: [1,4,3] } ];
$scope.display = function(x) {
    angular.forEach(x.picture, function(val,key){
        console.log(val);
        if (val === 4) {
            console.log("true");
            return true;
        } else {
            console.log("false");
            return false;
       }
    });
  };
});

4 Answers 4

1

It's not ngIf, it's your method that doesn't return true (it returns undefined which is falsy value). You need to understand that returning from forEach doesn't propagate outside as function return. In your case, you can use convenient Array.prototype.some method:

$scope.display = function(x) {
    return x.picture.some(function(val, key) {
        return val === 4;
    });
};

Demo: https://jsfiddle.net/hzdyhx4n/2/

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

Comments

0

your $scope.display method returns undefined, and ng-if evaluates undefined to false, hence nothing is displayd

Comments

0

Try using this scheme:

    angular.module('app', [])
    .controller('ctrl', function($scope) {
        $scope.z = [1,2,3];
        $scope.display = function(x) {
         return x(function(val, key) {
            return val === 1;
         });
        };
    });

    <div ng-app="app" ng-controller='ctrl'>
       <div ng-repeat=" x in z"> 
           <div ng-if="display(x)" >  
               display this
           </div>
       </div>
    </div>

1 Comment

i can't use this actually i made a simple example but in my application i need to first use foreach to check an id then use return
0

bro try this code.. it's works

    <div ng-app="app5" >
<div ng-controller='ctrl'> 
    <div ng-repeat=" x in z" >  
        <png-if="display(x)" >display this<p>
    </div>
</div>
</div>

and

angular.module('app5', [])
.controller('ctrl', function($scope) {
    $scope.z = [ { name: 'aa', id: 20, picture: [,1,2,4,3] } ];
      $scope.display = function(x) {
        angular.forEach(x.picture, function(val,key){
            console.log(val);
            if (val === 4) {
                alert("ho");
                console.log("true");
                return true;
            } else {
                console.log("false");
                return false;
           }
        });
    };
});

2 Comments

<p ng-if="display(x)"> display this </p>
actually it returns false,true and it continuous based upon values..we need to break if return true..

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.