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 ?

2
  • 1
    Do you by chance have a JSFiddle or the like that demonstrates this problem? Commented May 23, 2013 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? Commented May 23, 2013 at 16:04

2 Answers 2

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

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

4 Comments

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, 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.
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, without seeing your sample, it is difficult to guess what might be happening.
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>

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.