我试图将数据分配给$scope变量.在我的$promise.then()函数中,它正确显示但在函数外部显示为undefined.以下是我的控制器代码:
angular.module('testSiteApp').controller('TestController',function ($scope,Tests) {
$scope.test = Tests.get({id: 1});
$scope.test.$promise.then(function(data) {
$scope.tasks = data.tasks;
console.log($scope.tasks);
});
console.log($scope.tasks);
});
then()函数内的结果:
[Object,Object,Object]
then()函数之外的结果:
undefined
我正在使用的’Tests’服务工厂如下:
angular.module('testSiteApp').factory('Tests',function($resource) {
return $resource('/api/test/:id',{id: '@id'},{ 'update': { method: 'PUT' } } );
});
即使我使用查询方法而不是get for my资源并将isArray设置为true,我仍然会遇到同样的问题.由于某种原因,数据没有绑定到then函数中的我的范围.
我很抱歉,如果这是一个重复的问题,但我到处寻找,只发现与$promise函数有关的未定义问题,在这种情况下不是问题.
在此先感谢您的支持.
解决方法
传递给.then()的函数将在从后端获取数据后调用.另一个console.log()(.then()之外的那个)将在发出请求后立即被调用,而不是在它完成之后被调用,因此任务是未定义的.
考虑时间(当然时间只是一个例子):
// time = 0.000 sec. You make a request to the backend
$scope.test = Tests.get({id: 1});
$scope.test.$promise.then(function(data) {
// time = 1.000 sec. Request is completed.
// data is available,so you assign it to $scope.tasks
$scope.tasks = data.tasks;
console.log($scope.tasks);
});
// time = 0.000 sec (!!!) This has been called NOT AFTER
// the callback,but rather immediately after the Tests.get()
// So the data is not available here yet.
console.log($scope.tasks);