0

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 ?

Sam
  • 13,934
  • 26
  • 108
  • 194
  • 1
    Do you by chance have a JSFiddle or the like that demonstrates this problem? – Michelle Tilley May 23 '13 at 15:59
  • Could you try with `op in $parent.person.testArray` instead? `$parent` isn't needed but just give it a shot if it works. Also, could you provide a plunkr or a fiddle where it does not work? – callmekatootie May 23 '13 at 16:04

2 Answers2

2

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

Community
  • 1
  • 1
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • ooh my bad. I don't use $parent in my code. I've added in my post by accident. So I do exactly what you are doing and I still can't display anything in the ng-repeat. I've updated the code in my original post. – Sam May 23 '13 at 16:57
  • @Sam, we'll need to see more of your code to help you. You may be using some Angular built-in or custom directives just before or inside the ng-repeat that might be creating additional scopes. – Mark Rajcok May 23 '13 at 17:11
  • I've made it work in a separate sample project. I don't know what's wrong in my application, I'll have to investigate further. However, I've noticed in the sample I've made, that instead of updating the parent's property, it creates a new property on the child scope. Is that normal behaviour ? I would have expected the parent scope's property to be updated rather... – Sam May 23 '13 at 18:24
  • @Sam, without seeing your sample, it is difficult to guess what might be happening. – Mark Rajcok May 23 '13 at 18:55
1

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>
Mathew Berg
  • 28,625
  • 11
  • 69
  • 90