Georgi Naumov
Georgi Naumov

Reputation: 4201

Advice on the correct use of ngModel

I' new to AngularJS and have a following ambiguity with usage of ngModel. I want to give to the user possibility to generate unlimited number of "name": "value" pairs. So I generating div with ng-repeat for every element from pair. Here is my html:

<div ng-app>

    <div ng-controller="TestCtrl">
         <input type="button" value="+" ng-click="addNewRow();"/>
        <div ng-repeat="a in range(itemsNumber)"><input type="text" name="key"/> : <input type="text" name="value"/></div>
    </div>
</div>

And the JavaScript:

function TestCtrl($scope) {
    $scope.itemsNumber = 1;
    $scope.range = function() {
        return new Array($scope.itemsNumber);
    };

    $scope.addNewRow = function () {
        $scope.itemsNumber++;
    }
};

Here is working js fiddle: http://jsfiddle.net/zono/RCW2k/ I want to have model for this generating items but not sure how to do it.

I would appreciate any ideas and tips.

Best regards.

Edit:

I have create other solution. It can be viewed in this fiddle http://jsfiddle.net/zono/RCW2k/8/ But is this solution is good idea?

Upvotes: 1

Views: 127

Answers (1)

Ilan Frumer
Ilan Frumer

Reputation: 32377

Here is a fiddle: http://jsfiddle.net/RCW2k/13/

You should just create an array on the scope and it's also your model:

controller:

function TestCtrl($scope) {    
    $scope.items = [{key:"hello",value:"world"}]

    $scope.addNewRow = function () {
        $scope.items.push({key:"",value:""});
    }
};

html:

<div ng-controller="TestCtrl">
     <input type="button" value="+" ng-click="addNewRow();"/>
    <div ng-repeat="item in items">
        <input type="text" name="key" ng-model="item.key"/> : 
        <input type="text" name="value" ng-model="item.value"/>
    </div>
</div>

Upvotes: 2

Related Questions