在某些情况下,我想退出我的 $scope 函数。我正在尝试使用 return。但不幸的是它只从每个循环返回,而不是从主作用域函数返回。在我的代码中,即使 d.xyz 是 true f2 函数也会被调用。如果 d 的 xyz 为真,我想退出 f1。
$scope.f1 = function(){
angular.foreach(data, function(d){
if(d.xyz){
return; // tried with return false also
}
if(d.abc){
//some code
}
$scope.f2();
})
}
最佳答案
你不能真正退出angular的forEach函数。您能做的最好的事情就是确保在退出条件为真后每次迭代都返回回调。
所以你会这样做:
$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();
})
}
关于javascript - 如何在angular js中返回或退出$scope函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46072653/