In certain condition, I want to exit from my $scope function.I am trying this using return. But no luck it returns only from each loop, not from the main scope function. In my code, even d.xyz is true f2 function is getting called. I want to exit from f1 if xyz of d gets true.
$scope.f1 = function(){
angular.foreach(data, function(d){
if(d.xyz){
return; // tried with return false also
}
if(d.abc){
//some code
}
$scope.f2();
})
}
In certain condition, I want to exit from my $scope function.I am trying this using return. But no luck it returns only from each loop, not from the main scope function. In my code, even d.xyz is true f2 function is getting called. I want to exit from f1 if xyz of d gets true.
$scope.f1 = function(){
angular.foreach(data, function(d){
if(d.xyz){
return; // tried with return false also
}
if(d.abc){
//some code
}
$scope.f2();
})
}
Share
Improve this question
edited Sep 6, 2017 at 10:24
Kavitha Velayutham
asked Sep 6, 2017 at 10:17
Kavitha VelayuthamKavitha Velayutham
7031 gold badge10 silver badges29 bronze badges
5 Answers
Reset to default 2You can't really exit from angular's forEach function. The best you can do, is make sure the callback is returned every iteration after your exit condition is true.
So you would do it like this:
$scope.f1 = function(){
var stopRunning = false;
angular.foreach(data, function(d){
if(stopRunning){
return;
}
if(d.xyz){
stopRunning = true;
return;
}
if(d.abc){
//some code
}
$scope.f2();
})
}
angular.module("test",[]).controller("testC",function($scope){
$scope.data = [{"test":1},{"test":2}];
$scope.IsExist=false;
$scope.testF=function() {
for(var i=0;i<$scope.data.length;i++){
if($scope.data[i].test==1){
alert(1);
$scope.IsExist=true;
}else if($scope.data[i].test){
}
if($scope.IsExist)
{
return false;
}
$scope.testF();
}
}
$scope.testF();
});
<script src="https://ajax.googleapis./ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="testC">
</div>
$scope.f1 = function(x = true){
angular.foreach(data, function(d){
if(d.xyz){
x = false;
return; // tried with return false also
}
if(d.abc){
//some code
}
$scope.f2();
})
if (!x){
return;
}
}
Basically you are not exiting f1()
. This will do that for you.
You should use return statement in your function. It is not exiting as you are using return in angular.foreach callback function. Try using outside.
I think You should use break;
. if You are using return;
this works like a continue;
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745420628a4626949.html
评论列表(0条)