简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM