1

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?

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.