Arp
Arp

Reputation: 31

How to give dynamic values to ng-model

I am appending a div into the DOM on user click. To get the user entered values I want to attach ng-model to input fields. As I don't know the total number of div's which user will append, I want to keep the values in ng-model dynamic.

Here is the code: (my-Controller)

function addDiv() {
        var element = angular.element(document.createElement('my-Directive'));
        var el = $compile(element)($scope);

        //where to place the element
        angular.element($('#add')).append(element);
        $scope.insertHere = el;

        //giving unique id to div element.
        var objName = 'step'+number;
        dataCtrl.tbt = {
            "val": objName,
            "tes":"arjun"
        }
        $(element).attr("id",objName);
        console.log(objName);
        number++;
    };

//html where I want to put dynamic ng-model

<div class="form-group">
<div class="col-xs-4">
    <label for="target">Target:</label>
</div>
<div class="col-xs-7">
    <input id="target" placeholder="Target" ng-model="dataCtrl.tbt[dataCtrl.tbt.val]" type="text" class="form-control"/>
</div>

Upvotes: 0

Views: 1123

Answers (1)

Naghaveer R
Naghaveer R

Reputation: 2944

You can use ng-repeat to add input boxes dynamically

   <div ng-repeat="in in input">  
      <label>{{$index+1}}</label><input type="text" ng-model="in.value">
   </div>
<button ng-click="addInput()">Add</button>

And push an empty value to the Array on ng-click of add button

Plunker Link

Hope this Helps!!

Upvotes: 1

Related Questions