typ*_*uel 7 javascript angularjs angular-resource angularjs-scope angular-promise
我试图将数据分配给$ 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函数有关的未定义问题,在这种情况下不是问题.
在此先感谢您的支持.
kam*_*uel 13
传递给的函数.then()将在从后端获取数据后调用.另一个console.log()(外面的那个.then())将在请求完成后立即调用,而不是在完成后调用,因此tasks未定义.
考虑时间(当然时间只是一个例子):
// 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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22544 次 |
| 最近记录: |