1

My question is more about what would be the best practice in this scenario:

I have a form that has to allow a user to input n number of ideas, each idea in an independent text field. Ideally there would be a couple of buttons next to the last text input to allow the user to create a new text input or to erase the latest one.

I know DOM manipulation is not the way to go with Angular but due to requirements, I have to do something that requires creating elements dynamically. Is there a best practice, service or directive in Angular that could allow me to do this or I should just inject the elements with jQuery?

Marcelo C.
  • 118
  • 2
  • 10
  • possible duplicate of [Binding ng-model inside ng-repeat loop in AngularJS](http://stackoverflow.com/questions/14410993/binding-ng-model-inside-ng-repeat-loop-in-angularjs) – j.wittwer May 21 '14 at 15:23

2 Answers2

3

The only thing you need is proper use of ng-repeat. No DOM manipulation with jQuery is necessary. Nor would it be good practice. Behold, the power of ng-repeat.

Working plunker here.

user2847643
  • 2,893
  • 14
  • 22
3

Something like this?

<div ng-repeat="idea in ideas">
    <input ng-model="idea">
</div>
<button ng-click="AddNew()">Add New Idea</button>
<button ng-click="DeleteLast()">Delete Last Idea</button>

In controller:

$scope.AddNew = function() {
    $scope.ideas.push("");
}

$scope.DeleteLast= function() {
    $scope.ideas.splice($scope.ideas.length-1, 1);
}
Tong Shen
  • 1,364
  • 9
  • 17