angularjsformsangularjs-ng-repeatng-bindng-submit

How to update scope on form Submit, when ng-model value changes?


I am creating an edit customer form and passing an object of 30 key value pairs. I am then using ng-repeat to populate input fields of a form. All form is displayed nicely and with passed key, values. I can also change the value of any input field.But when I submit the form, it takes the old scope object which I passed initially in the form, leaving behind my changes. I need to submit my changed object Now. How To do that? I searched much but can't find the solution to this.

  var app = angular.module("customerModule", []);
app.controller('crudController', function($scope, $http) {
  $scope.Customers = //object from Ap with almost 30 key,values

    $scope.edit = function() {
      console.log($scope.Customers);
      //the above line prints the API called object where as I am editing the values of ng-model in my form. and I need the form submitted values
    }


});
<div ng-app="customerModule" ng-controller="crudController">
  <form name="as" ng-submit="edit()">
    <ul>

      <li ng-repeat="(key, val) in Customers  " ng-hide="(key=='total' || key=='paid' || key=='customfields' || key=='owing')" ng-if="key!='customfields'">

        <label class="label"> {{key}}</label> <input type="text" ng-model="val" />
      </li>

      <li ng-repeat="(key, val) in Customers.customfields">
        <label class="label"> {{key}}</label> <input type="text" ng-model="val" />

      </li>
      <button type="submit"><i class="fa fa-plus-circle" aria-hidden="true"></i><span> Edit Customer</span></button>
      <ul>

  </form>

</div>


Solution

  • Use ng-model="Customer[key]".

    You're using the local variable val referencing the value. That's basically aquivalent to doing

    var val = Custom['foo'];
    val = 'newValue';
    

    That won't change the value of Custom['foo'], right?

    But the following will:

    Custom['foo'] = 'newValue';