Loney GG Loney GG - 1 year ago 50
AngularJS Question

Array with 2 properties, AngularJs

I need to save 2 Strings into an array like this:

array[0].name = "William"
array[0].dni = "00112233Z"


so i can use ng-repeat:

<ul>
<li ng-repeat="item in array">
{{item.name}}
{{item.dni}}
</li>
</ul>


But I don't know how to declare it in Angular, I keep getting this error no matter how i try: TypeError: Cannot set property 'name' of undefined.

Here's the code where I'm getting the data:

$scope.array=[];
$scope.initial = function () {
$http.get('data/people.json').success(function (data) {
$scope.jsonData = data;
for(var i=0; i<$scope.jsonData.persons.length;i++){
$scope.array[i].name=$scope.jsonData.persons[i].person.nombre;
$scope.array[i].dni=$scope.jsonData.persons[i].person.dni;
}
});
};


Any help would be appreciated.

Regards.

Answer Source

You have to set an object first inside the array to assign properties like:

$scope.array=[];
$scope.initial = function () {
    $http.get('data/people.json').success(function (data) {
          $scope.jsonData = data;
          for(var i=0; i<$scope.jsonData.persons.length;i++){
            $scope.array[i] = {};
            $scope.array[i].name=$scope.jsonData.persons[i].person.nombre;
            $scope.array[i].dni=$scope.jsonData.persons[i].person.dni;
          }
    });
};

Otherwise array[i] is undefined because is an empty array

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download