当我尝试获取变量时 $scope 行为不正确
$scope not behaving correctly when I try to get a variable
我有一项服务 ThingsService,它与我的 API 通信。在 this great answer 之后,我还有一个 SharedData 服务。据我所知和测试,SharedData 不是问题。
控制器 ThingsController 使用此服务将数据引入应用程序,如下所示:
$scope.getThing = function(id){
ThingsService.GetThing(id,
function(response){
$scope.thing = response;
},
function(){
alert("Error");
});
};
$scope.getThing(SharedData.getNextThingId());
console.log($scope.thing); // => undefined
console.log($scope); // => thing, among others
现在,当我尝试访问 $scope.thing
时,它 returns 未定义。
有趣的是,如果我做类似 console.log($scope)
的事情,就会有一个名为 thing 的对象,而且所有适当的数据都设置在这个对象中。
有人知道发生了什么事吗?我很确定我错过了什么。
更新:根据 Mathew 的回答,此片段
$scope.getThing = function(id){
ThingsService.GetThing(id,
function(response){
$scope.thing = response;
$scope.doStuffwhenThingIsReady(); //<- Here $scope.thing is set :)
},
function(){
alert("Error");
});
};
挽回局面。
这很可能是因为 ThingsService.getThing
发生在 angular 之外(通过 post 或您有什么),所以之后直接进行控制台日志记录不会显示它。如果您控制台记录 $scope
虽然它是一个参考,所以当您打开它时您会看到它,因为 ThingsService.getThing
到那时可能已经完成。您必须等到 ThingsService.getThing
完成后才能使用 $scope.thing
.
我有一项服务 ThingsService,它与我的 API 通信。在 this great answer 之后,我还有一个 SharedData 服务。据我所知和测试,SharedData 不是问题。
控制器 ThingsController 使用此服务将数据引入应用程序,如下所示:
$scope.getThing = function(id){
ThingsService.GetThing(id,
function(response){
$scope.thing = response;
},
function(){
alert("Error");
});
};
$scope.getThing(SharedData.getNextThingId());
console.log($scope.thing); // => undefined
console.log($scope); // => thing, among others
现在,当我尝试访问 $scope.thing
时,它 returns 未定义。
有趣的是,如果我做类似 console.log($scope)
的事情,就会有一个名为 thing 的对象,而且所有适当的数据都设置在这个对象中。
有人知道发生了什么事吗?我很确定我错过了什么。
更新:根据 Mathew 的回答,此片段
$scope.getThing = function(id){
ThingsService.GetThing(id,
function(response){
$scope.thing = response;
$scope.doStuffwhenThingIsReady(); //<- Here $scope.thing is set :)
},
function(){
alert("Error");
});
};
挽回局面。
这很可能是因为 ThingsService.getThing
发生在 angular 之外(通过 post 或您有什么),所以之后直接进行控制台日志记录不会显示它。如果您控制台记录 $scope
虽然它是一个参考,所以当您打开它时您会看到它,因为 ThingsService.getThing
到那时可能已经完成。您必须等到 ThingsService.getThing
完成后才能使用 $scope.thing
.