Search code examples
javascripthtmlangularjsformsdata-binding

Angular form with dynamic input values


I am having issues with angular not picking up the dynamic values from my inputs.

This is what I'm trying to do. When a user clicks on map, the angular populates the hidden form fields with lat/lon, and the user then submits the form, which ends up missing data on the controller.

Here is the relevant controller code :

$scope.formData = {};

    $scope.submit = function(addressform) {
      addressService.createAdddress($scope.formData).then(function(result) {
        $scope.addressResponse = result;
      }, function(err) {
          alert(err);
      });
    }

    $scope.userSelectedPoint = function () {
      $scope.lat = map.getLat();
      $scope.lon = map.getLon();
      $scope.address = map.getAddress();
    }

This is the relevant HTML :

<form id="address_form" name="addressform" ng-submit="submit(addressform)">

   <input "lattitude" name="lattitude" type="hidden" ng-model="formData.lattitude" value="{{lat}}">
   <input id="longitude" name="longitude"type="hidden" ng-model="formData.longitude" value="{{lon}}">

   <p>Selected Address: {{address}}</p>
</form>

Everything looks ok in the chrome inspector(random point on a map) :

enter image description here

However when I submit this form and print out a $scope.formData I get an empty object:

$scope.formData
Object {}

What am I doing wrong here? Why is the formData in my controller empty, when obviously the value is set in the HTML as it can be seen from the screenshot I pasted?


Solution

  • you need to assign the values to ng-model variable, not to the value

    as

    <input "lattitude" name="lattitude" type="hidden" ng-model="formData.lattitude" />
    <input id="longitude" name="longitude"type="hidden" ng-model="formData.longitude" />
    

    assign the value to formData.lattitude.

    $scope.formData = {};
    $scope.userSelectedPoint = function () {
      $scope.formData.lattitude = map.getLat();
      $scope.formData.longitude  = map.getLon();
      $scope.formData.address = map.getAddress();
    }
    

    in angular if you provide a value to a variable and u assign that variable to input using ng-model then the input is getting the value of variable, anf if we change input value variable value gets change.

    so your assign the lattitude property of formData object to a input. that means if you change the $scope.formData.lattitude input value gets change.