2

How do I bind an ng-model that is an array to a fixed number of textboxes?

Let's say I have three textboxes and they are all optional, how do you bind the ng-model to those textboxes?

<input type="text" name="optionalField[]">
<input type="text" name="optionalField[]">
<input type="text" name="optionalField[]">

You can type into any textbox (e.g. textboxes 2 and 3 only) and when you save it, it's just going to be optionalField: ['text2', 'text3'].

Where you place the text doesn't matter; what matters is the order of the textboxes. So when you show the view again, it's just going to be bound to the first and second textboxes. If you only typed on the textbox 3, it will be bound to textbox 1 and so on.

UPDATE:

Just used dfsq's answer and modified it to return a filtered array of values. http://codepen.io/anon/pen/ozpxGq?editors=1011

2 Answers 2

2

In ng-repeat you can use $index

<input type="text" name="optionalField[]" ng-model="optionalField[$index]">
Sign up to request clarification or add additional context in comments.

2 Comments

I'm not going to use ng-repeat because there is going to be a fixed number of textboxes.
What do you mean by array of string ? can you give me example ?
0

Like this:

<input type="text" name="optionalField[]" ng-model="optionalField[0]">
<input type="text" name="optionalField[]" ng-model="optionalField[1]">
<input type="text" name="optionalField[]" ng-model="optionalField[2]">

1 Comment

I tried this but got an object instead of an array. Is it possible to get the array of strings instead of having to convert it into an array? codepen.io/anon/pen/ozpxGq?editors=1011

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.