Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

When creating input[text] fields, you assign an ng-model object to it. That ngModel is hardcoded in the scope like $scope.userName or $scope.lastname.

My problem is that i have a click event that adds input fields on demand. That means that i can't hardcode those object.

What I did is make them array blocks, with scope object...

$scope.example = {
    counter: 0,
    data: []
}

counter property would be incremented every type the input field is created on a user click event. So, ng-model property would be like this...

ng-model="example.data[example.counter]"

If the user creates 3 input fields, there would be 3 array values.

The problem is that those array values are not updated on model changes. Only the first input field is populated in the example.data array but on the third (2) index.

What am I doing wrong? Also, is there an angular way of dynamiclly creating input fields. This was my first raw try but I have a couple of ideas that involve broadcasting an event which are much more elegant.

share|improve this question
up vote 3 down vote accepted

Just use ng-repeat, like:

<input type="text" ng-repeat="myinput in myinputs" ng-model="myinput">
</input>

And when u need new input - just add new value to myinputs array.

share|improve this answer

Petr Averyanov answer was great and simple but it still didn't bind the model to the input values.

I managed to do that like this...

 <input type="text"
        ng-repeat="data in innerBlock.data track by $index"
        ng-model='innerBlock.data[$index]'>

track by $index is neccessary if you put the same value in every index of the array.

And the guts of the directive...

scope.example.counter++;
scope.example.data[scope.example.data.length] = '';

I was brainstorming a really complicated way but this is just too simple its great.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.