Search code examples
javascriptangularjsangular-ngmodel

Angular ng-model values not registered on submit


I know the title is kind of ambiguous but here is the issue: I have 2 input fields in a form that look like this:

<form name="modifyApp" class="form-signin" ng-submit="modify(val)">
   <input type="text" class="form-control" ng-model="val.name" id="appName">
   <input type="number" class="form-control" ng-model="val.number" id="number" min="0" max="65535">
   <button type="submit">Submit</button>
</form>

When I load the page I populate those two with some values from inside the controller:

angular.module('myApp').controller('modifyAppController', ['$scope', function($scope) {
    function setFields(appName, appNumber){
        document.getElementById("appName").value = appName
        document.getElementById("number").value = appNumber
    }

    $scope.modify= function(val){
        console.log(val)
    }
}])

The problem is when I press the Submit button. The values won't get registered unless I change them. For example, if I press the Submit button nothing gets printed, but if I change the number or the name, it gets printed.


Solution

  • In your controller you can simply initialize the val object like this:

    angular.module('myApp', [])
    
    .controller('modifyAppController', ['$scope', function($scope) {
    
      $scope.val = {
        name: '',
        number: 0
      };
    
      function setFields(appName, appNumber) {
        $scope.val.name = appName;
        $scope.val.number = appNumber;
      }
    
      $scope.modify = function(val) {
        console.log(val);
      };
    }]);