javascriptangularjsformsangularjs-ng-value

Form input ng-value seems filled but is empty


I am building an AngularJS app. I have a problem with a form that is filled with ng-value.

The input field is filled in, the user can see text but when the user presses the 'change' button it becomes undefined. Any thoughts?

My controller code:

// Fictional data it wineById will be a JSON object.
$scope.wineById = {"id":"4","name":"fdfvs1","percentage":"vcxz1"}

$scope.edit = function () {
    var wine = {
        id:$scope.wineById.id,
        name:$scope.name,
        percentage:$scope.percentage
    };

    console.log($scope.name, $scope.percentage);
};

HTML:

<form novalidate ng-submit="edit()">
        <label>ID wine: <input type="text" ng-value="wineById.id" ng-model="id" ng-disabled="true"></label> <br>
        <label>Name wine: <input type="text" ng-value="wineById.name" ng-model="name"></label> <br>
        <label>Percentage wine: <input type="text" ng-value="wineById.percentage" ng-model="percentage"></label> <br>

        <input type="submit" value="Change">
</form>

Case 1:

Got existing input in my fields. Pressing the button without changing the input data in the fields. Everything becomes undefined.

Case 2 (the one that works):

Got existing input in my fields. Changing all the fields with different data and pressing the button. Everything is changed.

How can I fix case 1?


Solution

  • Change your html as following if you still want to use ng-value for whatever reason:

    <form novalidate ng-submit="edit()">
      <label>ID wine:
       <input type="text" ng-init="id=wineById.id" ng-model="id" ng-value="wineById.id" ng-disabled="true">
      </label>
      <br>
      <label>Name wine:
        <input ng-init="name=wineById.name" type="text" ng-value="wineById.name" ng-model="name">
      </label>
      <br>
      <label>Percentage wine:
        <input ng-init="percentage=wineById.percentage" type="text" ng-value="wineById.percentage" ng-model="percentage">
      </label>
      <br>
      <input type="submit" value="Change">
    </form>
    

    Better approach would be to use just ng-model (unless you don't want two way binding)

    <form novalidate ng-submit="edit()">
        <label>ID wine:
          <input type="text" ng-model="wineById.id" ng-disabled="true">
        </label>
        <br>
        <label>Name wine:
          <input type="text" ng-model="wineById.name">
        </label>
        <br>
        <label>Percentage wine:
          <input type="text" ng-model="wineById.percentage">
        </label>
        <br>
    
        <input type="submit" value="Change">
    </form>
    

    Live Demo