angularjsangularjs-scopeangular-ngmodelangularjs-ng-value

How to make ng-model work with ng-value?


I have this input:

<input type="number" id="totWeight" ng-model="totWeight" ng-value="getTotWeight()" />

which value is calculated based on other fields, but it can also be inserted manually via the input field.

The problem is that when it's calculated, ng-model remains empty, so I tried to assign the calculated value if (!$scope.totWeight) when I send the data to the server, which is not optimal. Further if I insert a value via the input field and then change the other fields mentioned above which trigger the getTotWeight() function, the $scope.totWeight has a value so it won't get updated with the above if (!$scope.totWeight).

Sorry, I don't know how to explain it. Hopefully someone can help me with that.


Solution

  • The purpose of the NgValue directive is as the docs says

    It is mainly used on input[radio] and option elements, so that when the element is selected, the ngModel of that element (or its select parent element) is set to the bound value.

    So when using input type "number" you should not use it as it's value actually will be in the NgModel instead.

    If you want to trigger an event when the input is change, key is press etc you should use the NgChange, NgKeypress etc instead to trigger the function. The value will be keept in the NgModel for all situations.