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?

2 Answers 2

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 !

Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.