我有一个用ngResource定义的工厂:
App.factory('Account', function($resource) {
return $resource('url', {}, {
query: { method: 'GET' }
});
});
Run Code Online (Sandbox Code Playgroud)
我正在多次调用此工厂上定义的查询方法.调用可以异步发生,但我需要等待两个调用完成才能继续:
App.controller('AccountsCtrl', function ($scope, Account) {
$scope.loadAccounts = function () {
var billingAccounts = Account.query({ type: 'billing' });
var shippingAccounts = Account.query({ type: 'shipping' });
// wait for both calls to complete before returning
};
});
Run Code Online (Sandbox Code Playgroud)
是否有办法使用ngResource定义的AngularJS工厂,类似于jQuery的$ .when().then()功能?我宁愿不将jQuery添加到我当前的项目中.
我试图将一个承诺绑定到一个视图.我不知道你是否可以直接这样做,但这就是我想要做的.我有什么想法我做错了吗?
注意:源有一点设计超时并使用静态数据,但这是为了使代码更容易诊断.
编辑: JSFiddle页面:http://jsfiddle.net/YQwaf/27/
编辑:解决方案:事实证明,你可以直接绑定承诺.我的原始代码有两个问题:
HTML:
<div ng:controller="addressValidationController">
Region Code <select ng:model="regionCode" ng:options="r.code as r.name for r in getRegions()"/>
Country Code<select ng:model="countryCode"><option value="US">United States</option><option value="CA">Canada</option></select>
</div>
Run Code Online (Sandbox Code Playgroud)
JS:
function addressValidationController($scope, $q) {
var regions = {
US: [{code: 'WI',name: 'Wisconsin'}, {code: 'MN',name: 'Minnesota'}],
CA: [{code: 'ON',name: 'Ontario'}]
};
$scope.getRegions = function () {
var deferred = $q.defer();
setTimeout(function () {
var countryRegions = regions[$scope.countryCode];
console.log(countryRegions);
if(countryRegions === …Run Code Online (Sandbox Code Playgroud)