1

This might sound like a silly question but I've been stuck on this one for a few hours. There must be something amazingly simple I'm overlooking.

I've got an ng-repeat directive which is outputting a list of items:

<div ng-controller="MyCtrl">
    <div ng-repeat="foo in bars">
    ....
    </div>
</div>

And then inside, at the end of the list I've got a form to add to the list:

<div class="add">
    <input ng-model="valueToAdd" class="weight" />
    <a ng-click="addStuff()" class="button-small"> + Add</a>    
</div>

The addStuff() method is on my controller:

function MyCtrl($scope) {
    $scope.addStuff= function () {
        alert($scope.valueToAdd);
    }
}

But $scope.valueToAdd always gives me undefined.

What am I missing?

EDIT: Here's a punker where this problem is reproduced: http://plnkr.co/edit/YoGdx8?p=preview

5
  • 1
    Seems to work just fine (plunker) Commented Jun 10, 2013 at 9:45
  • Hmm ok. Let me take a second look. Could be something outside of the code I copy/pasted as an example. Typical ;-) Commented Jun 10, 2013 at 11:33
  • 1
    maybe valueToAdd is outside the scope of MyCtrl Commented Jun 10, 2013 at 12:05
  • @Atrix1987 good call, I figured it wouldn't be but it might :) Commented Jun 10, 2013 at 12:17
  • Hi guys, just added a link to a plunker (I forked your plunker @robertklep and modified so it's more similar to my actual code and now I have the same problem there). Commented Jun 10, 2013 at 19:47

1 Answer 1

4

ng-repeat creates new scope for each of its repeated sections and so valueToAdd is bound to a variable on that inner scope, which is a child of the outer scope. When addStuff is called, it works because it accesses the method on the outer scope via scope inheritance, but the variable it tries to reference is not defined in that outer scope.

Try passing the value to addStuff instead:

ng-click="addStuff(valueToAdd)"

Here is a forked Plunk

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

1 Comment

BINGO! That makes a whole lot of sense. Thanks!

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.