Reputation: 195
i am new to angularjs and i am learning promise in angular. I made a simple sample to understand how the promise works
<body ng-controller="sampleController">
<div>{{one}}</div>
<br/>
<br/>
<div>Status - {{two}}</div>
<br/>
<br/>
<div ng-click="callback()">click</div>
</body>
<script>
function sampleController($scope, $q, $timeout) {
$scope.one = "Hello World"
$scope.two = "NA"
$scope.callback = function() {
$timeout(function() {
$scope.one = "Good Evening"
}, 2000);
}
change = function() {
$scope.two = "Changed"
}
var defer = $q.defer()
var promise = defer.promise;
promise = promise.then($scope.callback()).then(change());
}
</script>
JSBin : http://jsbin.com/foxacawa/1/edit
By using the promise, i trying to change the status once the Hello world changes to Good Evening but i am not getting the output. what the right approach? Please suggest
Upvotes: 1
Views: 429
Reputation: 4457
Additionally: with
promise = promise.then($scope.callback()).then(change());
you're immediately invoking the $scope.callback and change functions and not of when the promise gets resolved.
Try
promise = promise.then($scope.callback).then(change);
Upvotes: 0
Reputation: 14122
the then()
callback will be called once the defer is resolved. To resolve the defer, simply use defer.resolve()
(or defer.reject()
to show failure)
I think that's what you might be looking for:
var defer = $q.defer()
$scope.callback = function(){
$timeout(function() {
$scope.one = "Good Evening";
defer.resolve('changed');
}, 2000);
}
just check the docs for $q for more details.
Upvotes: 1