繁体   English   中英

在AngularJS中使用$ http服务时的可变范围

[英]Variable scope when using $http service in AngularJS

我希望有人可以在使用$ 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循环位于成功方法调用的函数中,则此方法效果很好,但我认为将其保留在调用之外会更干净。 如果我在调用之外有循环,则会收到错误消息:

Error: $scope.tpRequests is null

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

您可以在$scope.tpRequests上使用$watch进行数据操作,但是如果没有其他方法可以触发监视并仅在操作前检查null / undefined ,我建议您仅在成功承诺中执行。

有关$watch$watchCollection用例的绝佳入门$watchCollectionhttp : //www.bennadel.com/blog/2566-scope-watch-vs-watchcollection-in-angularjs.htm

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM