Reputation: 464
I'm using Ionic to create an app, and in the controller, I'm getting an object that's resolved from the app.js. This object has several properties including an array like so:
{
"objectId":"id",
"objectName":"name",
"anArray":[{
"id":"id1",
"name":"name1",
"description":"Medium Rare",
"photographUrl":"/image1"
}, {
"id":"id2",
"name":"name2",
"description":"Baked Beans on Scrumptious Dark Rye Bread",
"photographUrl":"/image2"
}],
"emptyArray":[]
}
However, the problem is, I can iterate through each item in the array in the html using: (key, value) in theObject.anArray, but in the controller, I'm trying to iterate through the array in a for loop
for (var i = 0; i < $scope.theObject.anArray.length; i++) {...}
However, I get an error:
TypeError: Cannot read property 'length' of undefined
Can anyone help me figure out why I cannot access this array in the controller, but I can in the html. In fact, I can't access any property of the object in the controller, It appears as if the controller is instantiated before the object is resolved in the app.js using 'resolve', however, I was under the impression that this isn't supposed to happen, that the data was supposed to be resolved before the controller is instantiated
P.S. in the controller I use this:
$scope.theObject = theObject;
Thanks
Upvotes: 0
Views: 69
Reputation: 464
Ok, So I've solved the problem. Resolve returns a promise for the object before the controller is instantiated. However, the controller is instantiated before the object data from the web call is put into that promise object. So the solution is to make the web call inside the controller using this line
factory.theObject().get().$promise.then(function (response{
$scope.theObject = response;
}
Upvotes: 1
Reputation: 27222
You are getting below error because you don't have JSON
. You have an array: []
.
Try this :
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope) {
var theObject = [{
"objectId":"id",
"objectName":"name",
"anArray":[{
"id":"id1",
"name":"name1",
"description":"Medium Rare",
"photographUrl":"/image1"
}, {
"id":"id2",
"name":"name2",
"description":"Baked Beans on Scrumptious Dark Rye Bread",
"photographUrl":"/image2"
}],
"emptyArray":[]
}];
$scope.theObject = theObject;
var arr = $scope.theObject[0].anArray;
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
</div>
Upvotes: 0