Reputation: 1
I have a template that dynamically creates model names in an ng-repeat directive using the $index value. This is so I can increment the json element labels that are eventually passed. It's a field to select one of various dynamically created options. In the form of:
<ng-model="data.items['item' + ($index+2)]">
This has all worked great. I would like to add a new feature using a button attached to a function that is tied to whichever particular ng-repeat instance to which the button is tied. This feature clears the option field. So on the template side I do:
<ng-click="clearValue()" ng-disabled="!data.items['item' + ($index+2)]">
And I would like for the controller to pick this up. Clearly since the controller doesn't take the $index attribute, this doesn't work. If I hard code the number to test it, like the following:
$scope.clearValue = function() {
$scope.data.items.item2 = undefined;
};
It works great. But of course doing something like this does not:
$scope.clearValue = function() {
$scope.data.items['item' + ($index+2)] = undefined;
};
But of course hard coding it in makes it only work for that one particular value. Values are added dynamically with a function, so there could be one, or a hundred, or anywhere between.
Is there any way to make the clearValue function pick up any given model calling it, in the form above?
Upvotes: 0
Views: 181
Reputation: 2300
what you can do is you simply pass the $index back to controller in the function parameter
<ng-click="clearValue(($index+2))" ng-disabled="!data.items['item' + ($index+2)]">
$scope.clearValue = function(index) {
$scope.data.items['item' + (index)] = undefined;
};
Hope this help.
Upvotes: 0