I want angular.forEach to finish first and then update bulkUpdateCheck to false.
function bulkUpdate(curritems) {
$scope.bulkUpdateCheck = true;
angular.forEach(curritems, function (item) {
// multiple calls
});
$scope.bulkUpdateCheck = false;
}
I think your loop should complete before setting bulkUpdateCheck to true
Problem is, "multiple calls" that you are making, might be asynchronous. So things that are inside your loops needs to end.
Assuming you have asynchronous calls inside your forEach, you should
async function bulkUpdate(curritems) {
$scope.bulkUpdateCheck = true;
let multipleCalls = [] // this will keep all your promises
angular.forEach(curritems, function (item) {
// change this to promise you are using
const promise = Promise.resolve(3);
multipleCalls.push(promise)
});
await Promise.all(multipleCalls)
$scope.bulkUpdateCheck = false;
}
You can use the built in $q.all()
which will initialize a digest when it resolves.
Pass an array of $http
request promises to it that you create using Array#map()
angular.module('app', []).controller('main', ($scope, $q, $http, $timeout) => { const api_url = 'https://jsonplaceholder.typicode.com/todos/'; const todoIds = [1, 3, 6, 9, 12]; bulkUpdate(todoIds); $scope.todos = []; function bulkUpdate(curritems) { $scope.bulkUpdateCheck = true; // map arry of request promises const reqPromises = curritems.map(n => { return $http.get(api_url + n).then(res => res.data); }) // runs when all requests resolved $q.all(reqPromises).then(data => { // extra delay for demo to see visual difference $timeout(() => { $scope.bulkUpdateCheck = false; $scope.todos = data; console.log(data) }, 1500) }) } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <div ng-app="app" ng-controller="main"> <div ng-if="bulkUpdateCheck">Loading...</div> <div ng-repeat="item in todos"> <input type="checkbox" ng-checked="item.completed" /> {{item.title}} </div> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.