【发布时间】:2013-09-16 03:42:49
【问题描述】:
我有 AngularJs 控制器:
function MyController($scope, $http) {
// as $http.get() is async, success() returns promise but
// I need the actual value 'items'
var promise = $http.get(...)
.success(function(response) {return response.items;});
<waitForAjaxCall>
$scope.items = promise.get?();
$scope.firstItem = $scope.items[0];
//do stuff using $scope.firstItem
}
var myApp = angular.module('myApp',[]);
myApp.controller('MyController', ['$scope', '$http', MyController]);
如何确保$scope.items 在$scope.firstItem = ... 赋值之前由ajax 调用返回的值初始化?我看到的另一种方法是将 items 包装在调用 $http 的 angularjs 工厂中,但我仍然需要等待 ajax 调用在该工厂内完成。
【问题讨论】:
-
为什么不在 promise 的成功回调中设置 $scope.items 的值?
-
@Sneaksta adaiu,在这种情况下 $scope.firstItem 可能指的是未初始化的值
-
对了。没有在下一行看到对 $scope.items 的引用,抱歉。那么你不能在成功回调中定义 $scope.firstItem 吗?
标签: javascript ajax angularjs