我试图将诺言与观点捆绑在一起。我不知道您是否可以直接执行此操作,但这就是我要尝试执行的操作。有什么想法我做错了吗?
注意:源代码有点超时,并使用静态数据,但这使代码更易于诊断。
编辑: 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>
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 === undefined) { deferred.resolve([]); } else { deferred.resolve(countryRegions); } }, 1000); return deferred.promise; }; }
警告 :此答案在编写时是准确的,但是从1.2版本开始,Angular模板引擎无法透明地处理承诺!- @马尔沃里奥
是的,模板引擎(和表达式)透明地处理了promise,但是我会将promise分配给控制器中的作用域属性,而不是每次都返回一个返回新promise的函数(我认为这是您的问题,因为新承诺每次都会返回)。
JSFiddle:http : //jsfiddle.net/YQwaf/36/
<div ng:controller="addressValidationController"> Region Code <select ng:model="regionCode" ng:options="r.code as r.name for r in regions"/> Country Code<select ng:model="countryCode"><option value="US">United States</option><option value="CA">Canada</option></select> </div>
function addressValidationController($scope, $q, $timeout) { var regions = { US: [{ code: 'WI', name: 'Wisconsin'}, { code: 'MN', name: 'Minnesota'}], CA: [{ code: 'ON', name: 'Ontario'}] }; function getRegions(countryCode) { console.log('getRegions: ' + countryCode); var deferred = $q.defer(); $timeout(function() { var countryRegions = regions[countryCode]; if (countryRegions === undefined) { console.log('resolve empty'); deferred.resolve([]); } else { console.log('resolve'); deferred.resolve(countryRegions); } }, 1000); return deferred.promise; }; $scope.regions = []; // Manage country changes: $scope.$watch('countryCode', function(countryCode) { if (angular.isDefined(countryCode)) { $scope.regions = getRegions(countryCode); } else { $scope.regions = []; } }); }