gpt4 book ai didi

javascript - 在 AngularJS 中使用 $http 服务时的变量范围

转载 作者:行者123 更新时间:2023-11-28 07:53:05 25 4
gpt4 key购买 nike

我希望有人能够在使用 $http AngularJS 服务时阐明变量的范围。

我的代码如下所示:

app.controller('TestPlanRequestCtrl', function($scope, $http) {
$scope.tableData = []; // Populate the table with this array
$scope.tpRequests = null;
$http.get('common/data/requests.json').success(function(data) {
$scope.tpRequests = data.TPRequests;
});

接下来我想运行一个循环将数据放入数组中,如下所示:

for (var i = 0; i < $scope.tpRequests.length; ++i) {
var requestObj= {
requestNum: $scope.tpRequests[i].RequestNumber;
}
$scope.tableData.push(requestObj);
}

如果 for 循环位于从 success 方法调用的函数内部,则效果很好,但我认为将其保留在调用之外会更干净。如果我在调用之外有循环,则会收到错误:

错误:$scope.tpRequests 为空

我不明白为什么get调用中填充了tpRequests,然后get调用结束后数据就消失了。我猜测函数调用中的 $scope.tpRequests 与我在 $http.get() 上面声明的不同。正确的做法是什么?

最佳答案

您可以在 $scope.tpRequests 上使用 $watch 来进行数据操作,但是我建议如果没有其他的话,只在成功 promise 中执行此操作触发 watch 的方法,并在操作前简单地检查 null/undefined

关于 $watch$watchCollection 用例的精彩入门: http://www.bennadel.com/blog/2566-scope-watch-vs-watchcollection-in-angularjs.htm

关于javascript - 在 AngularJS 中使用 $http 服务时的变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26536698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com