Ark
Ark

Reputation: 457

adding a textbox element dynamically to a form by AngularJS

How can we add a textbox element to a form dynamically using AngularJs. For example in this case, I have a text and textbox which I want to add one other of this pair by clicking on a button using AngularJs.

<div ng-app>
<div ng-controller="ClickToEditCtrl">
    <div ng-hide="editorEnabled" ng-click="editorEnabled=true">
        {{title}}
    </div>
    <div ng-show="editorEnabled">
        <input ng-model="title">
        <button href="#" ng-click="editorEnabled=false">Done editing</button>
    </div>
</div>
</div>
<div>
<input type="text" placeholder="Enter answer">
</div>

Upvotes: 8

Views: 27494

Answers (3)

Pawan Kumar
Pawan Kumar

Reputation: 29

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
  <div ng-app="myApp" ng-controller="myCtrl">
    <ol>
       <li ng-repeat="element in elements">
         <input type="text" ng-model="element.value"/>
       </li>
    </ol>
    <br/>
    <b>Click here to add Textbox:</b><br/><input type="button" value="New Item" ng-click="newItem()"/>
    <br/>
    <br/>
    <b>Click here to see ng-model value:</b><br/>
    <input type="button" value="submit" ng-click="show(elements)">
  </div>
<script>
  var app = angular.module('myApp', []);
  app.controller('myCtrl', function($scope) {
    var counter=0;
      $scope.elements = [ {id:counter, value : ''} ];
      $scope.newItem = function(){
        counter++;
        $scope.elements.push(  { id:counter,value:''} );
    }
    $scope.show=function(elements) {
        alert(JSON.stringify(elements));   
    }
  });
</script>
</body>
</html>

Upvotes: 2

Ark
Ark

Reputation: 457

I implemented it myself. You could dynamically add an element by using ng-repeat in a

  • <li ng-repeat="elemnt in questionelemnt">
    

    Here it is the Demo: fiddle

    Upvotes: 9

  • Eriks
    Eriks

    Reputation: 306

    js file

    $scope.choices = [{id: 'choice1'}, {id: 'choice2'}, {id: 'choice3'}];
    
    $scope.addNewChoice = function() {
        var newItemNo = $scope.choices.length+1;
        $scope.choices.push({'id':'choice' +newItemNo});
    };
    
    $scope.showAddChoice = function(choice) {
       return choice.id === $scope.choices[$scope.choices.length-1].id;
    };
    

    html

    <div class="form-group" data-ng-repeat="choice in choices">
        <label for="choice" ng-show="showChoiceLabel(choice)">Choices</label>
            <button ng-show="showAddChoice(choice)" ng-click="addNewChoice()">Add another  choice</button>
        <input type="text" ng-model="choice.name" name="" placeholder="Enter a restaurant name">
    </div>
    

    Upvotes: 3

    Related Questions