小编typ*_*uel的帖子

AngularJS $ promise then()数据未定义

我试图将数据分配给$ 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); 

});
Run Code Online (Sandbox Code Playgroud)

then()函数内的结果:

[Object, Object, Object, Object]
Run Code Online (Sandbox Code Playgroud)

then()函数之外的结果:

undefined
Run Code Online (Sandbox Code Playgroud)

我正在使用的'Tests'服务工厂如下:

angular.module('testSiteApp').factory('Tests', function($resource) {

return $resource('/api/test/:id', {id: '@id'}, { 'update': { method: 'PUT' } } );

});
Run Code Online (Sandbox Code Playgroud)

即使我使用查询方法而不是get for my资源并将isArray设置为true,我仍然会遇到同样的问题.由于某种原因,数据没有绑定到then函数内的我的范围.

我很抱歉,如果这是一个重复的问题,但我到处寻找,只发现与$ promise函数有关的未定义问题,在这种情况下不是问题.

在此先感谢您的支持.

javascript angularjs angular-resource angularjs-scope angular-promise

7
推荐指数
1
解决办法
2万
查看次数