Angular way to collect values from several inputs

I have following trouble. I have several rows with dynamically generated inputs in AngularJS view. I'm searching elegant way to get array from this generated inputs. This is me html:

<div ng-app>

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

        <input type="button" value="Test" ng-click="showItems();"/>
    </div>
</div>

and this is my javascript code:

function TestCtrl($scope) {
    $scope.items = [
        {name: "", value: ""}
    ];

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

    $scope.removeItem = function (index) {
        $scope.items.splice(index,1);
    };    

    $scope.showItems = function() {
        alert($scope.items.toSource());
    }
};

alert($scope.items.toSource()); will work correct only under Firefox and as you can see array is empty. I'm searching a way to update array or other angular way method. document.querySelector("input[attr]") or jQuery similar is not good idea I think.

Here is working jsFiddle: http://jsfiddle.net/zono/RCW2k/21/

I would appreciate any advice and ideas.

Best regards.

Answers


Use ngModel:

The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.

Your view should look like:

<div ng-repeat="item in items">
  <input type="text" ng-model="item.name"/> : 
  <input type="text" ng-model="item.value"/>
  <input type="button"  value="x" ng-click="removeItem($index);"/>
</div>

(As for the use of toSource() in your code, it is not part of any standard - Gecko-only)

Working example: http://jsfiddle.net/rgF37/


Need Your Help

bootstrap3.0 typeahead plugin not working

javascript twitter-bootstrap bootstrap-typeahead

I am trying to get typeahead auto complete work and I don't see it is working.

Jython or JRuby?

python ruby jruby jython

It's a high level conceptual question. I have two separate code bases that serve the same purpose, one built in Python and the other in Ruby. I need to develop something that will run on JVM. So I ...