user1153484
user1153484

Reputation: 195

using promise in angularjs

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

Answers (2)

Robin Drexler
Robin Drexler

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

BiAiB
BiAiB

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

Related Questions