简体   繁体   中英

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.

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. 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. 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(). 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.

A great primer on use cases for $watch and $watchCollection : http://www.bennadel.com/blog/2566-scope-watch-vs-watchcollection-in-angularjs.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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