我正在构建一个票证管理表,但在尝试导出 ajax 函数外部的变量时遇到一些问题。
我的代码:
app.controller('bodyController',function($scope,$http,$sce){
$scope.ticketList = [];
$http.get("tickets.php")
.then(function(response) {
$scope.ticketModify = response.data;
console.log($scope.ticketModify); //this one return the correct data.
return $scope.ticketModify;
});
console.log($scope.ticketModify); //this return undefine
如果我尝试将 response.data
返回到任何变量中,结果与工厂相同
最佳答案
仅仅因为代码在物理上位于其他代码之上并不意味着它是从上到下执行的。像这样考虑你的程序:
app.controller('bodyController',function($scope,$http,$sce){
$scope.ticketList = [];
$http.get("tickets.php")
.then(handleResponse);
console.log($scope.ticketModify); //this return undefine
function handleResponse(response) {
$scope.ticketModify = response.data;
console.log($scope.ticketModify); //this one return the correct data.
return $scope.ticketModify;
}
现在您明白为什么 $scope.ticketModify
仍未定义了吗?代码的位置并不重要,重要的是它的执行时间。如果您想使用新修改的 $scope.ticketModify
执行更多操作,则应该将另一个 then
链接到您已有的 then
上。或者,调用另一个函数并从当前的 then
传递 $scope.ticketModify
。你可以做任何事!
关于javascript - Angular Ajax,函数外 undefined variable ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40051632/