使用承诺。 Angular 可以在没有任何“特殊干预”的情况下使用 Promise,就像为范围变量赋值一样,请参阅 plnkr。 Promise 是驯服异步编程以像同步编程一样工作的“基础”(虽然我们在浏览器中没有 javascript 生成器),并且受到 Angular 团队的鼓励,因为它具有高度的可测试性和可维护性
http://plnkr.co/edit/8BBS2a1kC24BHBWRYp9W?p=preview
// trying to emulate your service here
var app = angular.module('app', []);
app.factory('User', function($q, $timeout){
User = {};
User.validateEmail = function(email){
var d = $q.defer();
$timeout(function(){
if (/(yahoo|gmail)/.test(email.email)){
d.resolve(email); // return the original object, so you can access it's other properties, you could also modify the "email" object to have isValid = true, then resolve it
} else {
d.resolve(); // resolve it with an empty result
}
}, 1000, false);
return d.promise;
};
return User;
});
app.controller('MainCtrl', function(User, $q){
this.emails = [
{email: 'joe@gmail.com', name: 'Joe'},
{email: 'abc@fjkdsl.com', name: 'Abc'},
{email: 'xyz@yahoo.com', name: 'XYZ'},
{email: 'test@nknk.com', name: 'test'}
];
this.isEmailValidList = [];
var promises = [];
for(var i=0; i < this.emails.length; i++) {
promises.push(
User.validateEmail(this.emails[i])
);
}
$q.all(promises).then(function(emails){
this.isEmailValidList = emails.filter(function(e){ return e; });
}.bind(this));
});
注意:$timeout 用于模拟异步任务,例如数据库调用等。您可以将整个 emails 数组传递给验证服务,然后返回该数组,而不是创建一个中间的 promise 数组。使用 Angular,您可以将范围变量分配给 Promise,您可以在 ng-repeat 上使用它,而无需对代码进行任何更改