Currently, I am utilizing Angular in conjunction with jQuery Mobile to develop multiple pages, but I have encountered an obstacle when using the $http service to connect to my JSON requests. While populating a few arrays with functions and successfully retrieving data for my pages, I am occasionally facing errors such as:
Cannot read property 'length' of undefined
The snippet of my code contributing to this issue is as follows:
$http.jsonp(url).success(function(data) {
for (i=0; i<data.PROJECT.length; i++)
$scope.ProjectList.push( { id:data.PROJECT[i].PROJECT_CODE, name:data.PROJECT[i].PROJECT_DESC } );
});
The problem seems to arise within the 'For' loop section of my code. I attempted an alternative approach using "then", which looks like this:
var request = $http.jsonp(url);
return request.then(function(request) { return request.data.PROJECT; }, handleError );
Despite implementing this change, the same error persists, or sometimes there are no errors with blank results. Could anyone help identify what I might be doing incorrectly? Each API call has its own function, so object reusability should not be an issue (though there may be concerns about appending objects). Additionally, after separating my code into controller/service - part 2 of the project - I continue experiencing these errors.
UPDATE
To further illustrate the intermittent nature of this issue, I have set up a jsFiddle demo available here. Upon running the demonstration multiple times, you will observe that the arrays intermittently return empty values. If console logs were accessible, you would notice that ProjectList contains the resultset of EquipList at times, and vice versa.