Sat Sat - 2 years ago 84
AngularJS Question

How to set angularjs model value calculated from other two number fields

Hi I am currently working on one AngularJS ionic app but facing a problem in settings up model value in the view.
It a simple form with fields defined.

<input type="number" ng-model="form.field1" />
<input type="number" ng-model="form.field2" ng-change="count=form.field1+form.field2" />
<input type="number" ng-model="form.field3" ng-init="form.field3=count" ng-value="count"/>

On third field I can see the value displayed but when submit to server it had "0" not the counted value.

In the controller I had


Any help appreciated, new to AngularJS.

Answer Source

You don't need ng-change. You can just watch the variable and update it using $scope.$watch. You can remove ng-init and ng-value from your inputs too.

   var myApp = angular.module('myApp', []);
    myApp.controller('ctrl', ['$scope', function ($scope) {
        $scope.$watch('form.field1 + form.field2', function (value) {
        $scope.form.field3 = value;
<script src=""></script>
<div ng-app="myApp" ng-controller="ctrl">
<input type="number" ng-model="form.field1" />
<input type="number" ng-model="form.field2"/>    
<input type="number" ng-model="form.field3"/>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download