Reputation: 13806
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
Upvotes: 1
Views: 2207
Reputation: 63069
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)"
Upvotes: 4