简体   繁体   English

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

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

I'm hoping someone can shed some light on the scope of variables when using the $http AngularJS service. 我希望有人可以在使用$ http AngularJS服务时对变量的范围有所了解。

My code looks like this: 我的代码如下所示:

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;
    });

Next I want to run a loop to put my data into an array like so: 接下来,我想运行一个循环,将数据放入数组中,如下所示:

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

This works great if the for loop is inside the function called from the success method, but I think it would be cleaner to keep it outside the call. 如果for循环位于成功方法调用的函数中,则此方法效果很好,但我认为将其保留在调用之外会更干净。 If I have the loop outside the call, I get the error: 如果我在调用之外有循环,则会收到错误消息:

Error: $scope.tpRequests is null

I don't understand why tpRequests is populated in the get call, and then the data is gone after the get call ends. 我不明白为什么在get调用中填充了tpRequests,然后在get调用结束后数据就消失了。 I'm guessing it is considering the $scope.tpRequests inside the function call to be a different one than the one I declared above the $http.get(). 我猜想它正在考虑函数调用内的$ scope.tpRequests与我在$ http.get()上方声明的那个不同。 What's the correct way to do this? 正确的方法是什么?

You can use a $watch on $scope.tpRequests to do your data manipulation, however I would recommend just doing it in the success promise if there are no other ways to trigger the watch and simply check for null / undefined before operating. 您可以在$scope.tpRequests上使用$watch进行数据操作,但是如果没有其他方法可以触发监视并仅在操作前检查null / undefined ,我建议您仅在成功承诺中执行。

A great primer on use cases for $watch and $watchCollection : http://www.bennadel.com/blog/2566-scope-watch-vs-watchcollection-in-angularjs.htm 有关$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