使用的承諾。 Angular可以在沒有任何「特殊干預」的情況下使用promise,就像給scope變量賦值一樣,參見plnkr。承諾是「基地」馴服異步編程像同步編程工作(雖然我們沒有在瀏覽器中的JavaScript發電機),由角團隊鼓勵,因爲它的高度可測試性和可維護性
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: '[email protected]', name: 'Joe'},
{email: '[email protected]', name: 'Abc'},
{email: '[email protected]', name: 'XYZ'},
{email: '[email protected]', 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
是模擬一個異步任務,例如數據庫調用等,您可以通過電子郵件整個陣列到驗證服務,然後返回,而不是創建承諾的中間陣列的方向。隨着角度,你可以一個範圍變量分配給一個承諾,你可以使用它在ng-repeat
無需更改代碼
這工作得很好,感謝工作示例。 – Anubha