Search code examples
angularjsangularjs-directiveangularjs-scopeangularjs-ng-repeatangular-ngmodel

Angular - how to pass ng-model from ng-repeat to a function and to scope


I have the following code:

<form ng-submit="addRow($index)">
    <input type="text" ng-repeat="column in table.columns" ng-model="column">
    <input type="submit" value="add row">
</form>

Live code here:

http://jsfiddle.net/muehvxx1/

What I'm trying to do is that whenever you click on the "Add Row" button, a new object is added to the scope (to the form's parent object) passing all values from the form's fields.

So far you can add an object to the correct parent (that works), but it doesn't pass the fields' values.


Solution

  • You could do something like this http://jsfiddle.net/9g8vpnaa/

    HTML: Form

    <form ng-submit="addRow(table)">
      <input type="text" ng-repeat="column in table.columns" ng-model="table.newItem[column]">
      <input type="submit" value="add row">
    </form>
    

    JS: addRow()

    $scope.addRow = function(table){
      table.items.push(table.newItem);
      table.newItem = {};
    };