Reputation: 709
I'm making a form component that will allow you give a list of values and show input[number]
fields for each value in the list.
The problem is that it's a list of objects, not number primitives, and I need a good way to establish data-binding between my inputs and the number property in each object.
This number property would be dynamically set via a scope attribute on my component.
My data could look like the following
$scope.ngModelList = [{foo: 'bar', num: 1}, {foo: 'baz', num: 3}];
and my inputs look somewhat like this
<div class="inputs"
data-ng-repeat="model in ngModelList">
<input type="number"
data-ng-model="model">
</div>
Upvotes: 2
Views: 6566
Reputation: 843
<div class="inputs"
data-ng-repeat="model in ngModelList">
<input type="number"
data-ng-model="model.foo">
</div>
Something like?
Upvotes: 1
Reputation: 1422
You can use
<div class="inputs" data-ng-repeat="model in ngModelList">
<input type="number" data-ng-model="model.num">
</div>
When you use model.num as ngModel, it will be a 2 way binding to the num attribute of that particular model.
Upvotes: 0
Reputation: 709
When assuming that the object property we're going to be binding to is either fixed (not very useful) or if we require it to always be present, the answer is rather straightforward.
We'd simply require the property name as one of our directive's attributes, e.g. ngModelProperty
and have the following solution.
directive("multiNumberForm", function () {
return {
scope: {
ngModelList: "=", // Array<Object> of models to bind to
ngModelProperty: "@" // Property of each Object for actual binding
}
...
}
};
And in our template
<div class="inputs"
data-ng-repeat="model in ngModelList">
<input type="number"
data-ng-model="model[ngModelProperty]">
</div>
If however, if we specifically want
ngModelProperty
to be optional,ngModelProperty: "@?"
, the solution is less straightforward.
As soon as I find a solution for this, I'll post the answer here.
Upvotes: 1