1

trying to access controller variable in ng-repeat with same name. e.g.

Controller

$scope.items = [1,2,3,4,5];

$scope.a = {
  data: "Some Data"
};

View

<div ng-repeat="a in items"> {{ a }} - {{ $parent.a.data }} </div>

but it is not working. is it possible to access that variable (Object) inside ng-repeat with same name?

shah
  • 1,163
  • 2
  • 19
  • 40

2 Answers2

3

One way to make it, is accessing variables by naming your controller (Some example here in doc).

You can name your controller like ng-controller="TestCtrl as ctrl"

Then, you need some changes in your view :

<div ng-repeat="a in ctrl.items"> {{ a }} - {{ ctrl.a.data }} </div>

And in your controller :

app.controller('TestCtrl', function($scope) {
    var self = this;
    self.items = [1,2,3,4,5]; //brackets here, not curly brackets as said by @georgeawg 
    self.a = {
        data: "Some Data"
    };

    // Rest of you code
});

Finally, naming controllers is quite a good practice.

Hope it helps !

Jacques Cornat
  • 1,612
  • 1
  • 19
  • 34
1

If you intend $scope.items to be an array, use square brackets, not curly brackets.

//Do THIS
$scope.items = [1,2,3,4,5];
//NOT THIS
$scope.items = {1,2,3,4,5};

Your ng-repeat iterator can be anything. There is no need to overload a parent scope variable.

<div ng-repeat="anything in items"> {{ anything }} - {{ a.data }} </div>

Also if the parent variable is not overloaded, there is no need to use $parent.

The variables in elements repeated by ng-repeat prototypically inherit from the parent scope. For more information, see What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

Community
  • 1
  • 1
georgeawg
  • 48,608
  • 13
  • 72
  • 95