Abdo Adel February 2016

how to update form hidden data before submssion in AngularJS?

I have my model variables already bound to some hidden input fields in a form.

When the user hits the submit button, I try to update these fields by updating the corresponding bound model variables but they do not change (I noticed that when dumping the request on the server, I always receive the old data), also I noticed that every thing works O.K when I use normal text inputs rather than hidden inputs

Here is my code:

Form

<form name="bla bla" action="bla bla" method="post" ng-submit="updateForm()"> 
  <input type="hidden" name="token" ng-model= "extra.token" />
  <input type="hidden" name="filters" ng-model="extra.filters" />
  <button type="submit">
    submit form
  </button>
</form>

Controller

var app = angular.module(... // bla bla

app.controller('MyController', ['$scope', ctrlDef]);

function ctrlDef($scope) {
  $scope.extra = {};
  $scope.extra.token = '';
  $scope.extra.filters = '';

  $scope.updateForm = function() {
      $scope.extra.token = 'test1';
      $scope.extra.filters = 'test2';
  };
}

Answers


Joe Clay February 2016

I don't think ngSubmit will reliably be run before the POST request if you use the standard HTML form attributes (method, action, etc). A better idea would be to use the $html service to send your request. This also has the benefit of being asynchronous, so you shouldn't need a hidden iframe like you do at the moment.

app.controller('MyController', ['$scope', '$html', ctrlDef]);

function ctrlDef($scope, $html) {
  $scope.extra = {};
  $scope.extra.token = '';
  $scope.extra.filters = '';

  $scope.updateForm = function() {
      $scope.extra.token = 'test1';
      $scope.extra.filters = 'test2';

      $http.post(extra, "your post url here").then(function (response) {
          // do stuff with the response here...
      });
  };
}

Post Status

Asked in February 2016
Viewed 3,549 times
Voted 4
Answered 1 times

Search




Leave an answer