Sam
Sam

Reputation: 14586

angularjs: ng-repeat not working with parent scope property

In a child controller, I'm populating an array on the parent scope:

$scope.person.testArray = [{id: "test"},{id: "test2"}];

That works fine and the person property now has an extra property called testArray, which contains the above values.

Then in the view associated with the child controller, I want to display the values of the array:

<div ng-repeat="op in person.testArray">
  {{op.id}}
</div>

Nothing shows up.

However, I know it's related to the fact that I'm using ng-repeat. If, in the child controller I set a regular property on the person object, such as:

$scope.person.test = "test";

and then in the view I do:

{{person.test}}

it shows the string "test".

What am I doing wrong with ng-repeat ?

Upvotes: 0

Views: 3415

Answers (2)

Mathew Berg
Mathew Berg

Reputation: 28750

While like the others I suggest against using $parent, you should be able to use the ng-repeat like this:

<div ng-repeat="op in $parent.person.testArray">
  {{op.id}}
</div>

Upvotes: 1

Mark Rajcok
Mark Rajcok

Reputation: 364697

You shouldn't have to use $parent in your child controller, since the child controller's $scope prototypically inherits from the parent controller's $scope:

function ParentCtrl($scope) {
    $scope.person = {};
}

function ChildCtrl($scope) {
    $scope.person.testArray = [{id: "test"}, {id: "test2"}];
}

HTML:

<div ng-controller="ParentCtrl">
    <div ng-controller="ChildCtrl">
        <div ng-repeat="op in person.testArray">{{op.id}}</div>
    </div>
</div>

fiddle

Upvotes: 2

Related Questions