I am trying to connect a promise with a presentation. I donβt know if you can do it directly, but this is what I am trying to do. Any ideas what I'm doing wrong?
Note: the source is a bit contrived with a timeout and uses static data, but this makes it easier to diagnose the code.
EDIT: JSFiddle Page: http://jsfiddle.net/YQwaf/27/
EDIT: SOLUTION: It turns out that it can directly bind promises. I had two problems with my source code:
- Using setTimeout () instead of angular $ timeout was a problem. angular does not know that it needs to update the user interface when the timeout starts (you can solve this with $ scope. $ apply inside setTimeout or just use $ timeout)
- Binding to the function that returned the promise was a problem. If he is called a second time, this is another promise. It is best to set the scope variable and create a new promise if necessary. (In my case, it caused $ scope. $ Watch in the country code)
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; }; }
angularjs promise
Adam Tegen Oct 23 '12 at 14:45 2012-10-23 14:45
source share