Angular JS承诺评估

时间:2014-01-11 04:49:46

标签: angularjs angular-promise

更新:我挖得更深一些,发现在1.2.0之后角度已弃用auto-unwrapping of promises

我理解Angular JS会评估作为承诺的范围变量,然后在履行承诺时更新控制器的视图。

我的问题是:

http://jsfiddle.net/dhruvkaran/Lv5vF/4/

<div ng-app="myApp">
  <div ng-controller="DemoController">
    {{foo}}
  </div>
</div>

<script>
  var myApp = angular.module("myApp", []);

  myApp.controller('DemoController', function($scope) {
    $scope.foo = "bar";
  });
</script>

工作得很好,但是,

http://jsfiddle.net/dhruvkaran/Lv5vF/5/

<div ng-app="myApp">
  <div ng-controller="DemoController">
    {{foo}}
  </div>
</div>

<script>
  var myApp = angular.module('myApp', []);

  myApp.controller('DemoController', function($scope, $q) {
    var deferred = $q.defer();
    deferred.resolve("bar");
    $scope.foo = deferred.promise;
  });
</script>

没有。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:3)

您正在使用承诺错误。承诺是将来某个时候解决或拒绝的事情。另外:范围变量不一定是承诺,所以这可能是你感到困惑的地方。要正确使用promise,您需要使用promise的“then”函数添加回调:

myApp.controller('DemoController', function($scope, $q) {
  var deferred = $q.defer();
  deferred.resolve("bar");

  //Note: Promises are not normally resolved inline like above
  deferred.promise.then(function (data) {
     $scope.foo = data;
  });

});