所以我想转动我的#34; loading"用ng-show
打开和关闭gif。在脚本通过forEach
加载数组完成后,我特别想关闭它。
如何在forEach
完成整个周期"时运行代码。类似于.then()
的内容,但适用于for
循环
function selectAll(bool) {
vm.selectAllSpinner = true;
vm.practicesLeftCol = [];
if(bool === true){
vm.practices.forEach(function(practice){
practice.selected = true;
vm.practicesLeftCol.push(practice)
})
I want this after the foreach ->vm.selectAllSpinner = false;
} else if (bool === false){
vm.practices.forEach(function(practice){
practice.selected = false;
vm.practicesLeftCol = [];
})
I want this after the foreach ->vm.selectAllSpinner = false;
}
答案 0 :(得分:-1)
所以forEach
不是异步的。因此,你可以写下来:
function selectAll(bool) {
vm.selectAllSpinner = true;
vm.practicesLeftCol = [];
if(bool === true){
vm.practices.forEach(function(practice){
practice.selected = true;
vm.practicesLeftCol.push(practice)
})
} else if (bool === false){
vm.practices.forEach(function(practice){
practice.selected = false;
vm.practicesLeftCol = [];
})
}
vm.selectAllSpinner = false;
}
话虽如此,我认为代码一般可以清理得更像:
function selectAll(bool) {
vm.selectAllSpinner = true;
vm.practicesLeftCol = [];
if (bool) {
vm.practicesLeftCol = vm.practices.reduce(function(memo, practice) {
practice.selected = true;
memo.push(practice);
return memo;
}, []);
}
vm.selectAllSpinner = false;
}
同样,reduce
和forEach
都不是异步的,所以这应该有点工作......
答案 1 :(得分:-2)
在Javascript中,使用分号(;
)分隔符(可选地后跟换行符)将命令附加到上一个命令。因此
function selectAll(bool) {
vm.selectAllSpinner = true;
vm.practicesLeftCol = [];
if(bool === true){
vm.practices.forEach(function(practice){
practice.selected = true;
vm.practicesLeftCol.push(practice)
});
vm.selectAllSpinner = false; //<---
} else if (bool === false) {
vm.practices.forEach(function(practice){
practice.selected = false;
vm.practicesLeftCol = [];
});
vm.selectAllSpinner = false; //<---
}
}
答案 2 :(得分:-3)
不幸的是,每个没有回调 - 但你可以这样做:
if(bool === true){
vm.practices.forEach(function(practice){
practice.selected = true;
vm.practicesLeftCol.push(practice);
items++;
if(items === your_array.length) {
vm.selectAllSpinner = false;
}
})
}