2

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>

3 Answers 3

1

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.

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

Comments

1
<div class="inputs"
    data-ng-repeat="model in ngModelList">

    <input type="number"
        data-ng-model="model.foo">

</div>

Something like?

1 Comment

The ngModel attribute is two-way binded, so you'd need leave to off those curly braces. data-ng-model="model.foo"
0

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.

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.