1

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.