bboulahdid
bboulahdid

Reputation: 339

AngularJS - accessing a array of objects in a controller goes wrong


I'm trying to access an array of objects in my controller :

angular.module('schoolManagement').controller('CycleController', ['$scope', function($scope){
    $scope.cycles = [
        {
            nomCycle : 'Primaire',
            active   : 'oui'
        },
        {
            nomCycle : 'Collège',
            active   : 'non'
        }
    ];
    console.log($scope.cycles[0].nomCycle);
}]);

The console.log() gives exactly what i'm looking for the in console, but when i use ng-repeat to loop over the array in my view, it doesn't work :

<tbody ng-controller="CycleController as CycleCtrl">
    <tr ng-repeat="cycle in CycleCtrl.cycles">
        <td>
            <input type="checkbox" />
        </td>
        <td>{{cycle.nomCycle}}</td>
        <td>{{cycle.active}}</td>
    </tr>
</tbody>


EDIT :
Since i'm using $scope there is no need to use the controller syntax, the correct form in this :

<tr ng-repeat="cycle in cycles">...</tr>

Upvotes: 0

Views: 547

Answers (3)

Alvin Thompson
Alvin Thompson

Reputation: 5448

You don't need to qualify the array with the name of the controller, since it's in scope. Instead, just:

<tr ng-repeat="cycle in cycles">

Upvotes: 1

Numyx
Numyx

Reputation: 1758

If you use the controller as syntax, you need to change your controller to:

.controller('CycleController', [function() {
  this.cycles = [{
    nomCycle: 'Primère',
    active: 'oui'
  }, {
    nomCycle: 'Collége',
    active: 'non'
  }];
}]);

You don't need the $scope here. You may add it again, if you need things like watchers, etc.

Upvotes: 2

aorfevre
aorfevre

Reputation: 5064

I assume that line

<tr ng-repeat="cycle in CycleCtrl.cycles">

Shall be

<tr ng-repeat="cycle in cycles">

P.S: In french, Primère is spelled : PRIMAIRE

Upvotes: 1

Related Questions