2017-07-27 68 views
1

嗨我目前正在研究一個AngularJS離子應用程序,但在設置視圖中的模型值時遇到問題。 它是一個定義了字段的簡單表單。如何設置從其他兩個數字字段計算的angularjs模型值

<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"/> 

在第三個字段中,我可以看到顯示的值,但是當提交給服務器時,它具有「0」而不是計數值。

在控制器我有

$scope.form={}; 

任何幫助表示讚賞,新AngularJS。

+0

你能發佈您的代碼放在這裏,或使用引擎收錄/的jsfiddle等,所以我們可以看到它嗎?謝謝 – rrd

+0

嗨剛發佈。 – Sat

+0

我試過這個方法,但沒有運氣$ scope.count = 0.00; $ scope.addNumbers = function(b1,b2){ if(b1!== null && b2!== null) { $ scope.count = b1 + b2; $ scope.form.Total。$ setViewValue('$ scope.count'); angular.element('#Total')。controller('ngModel')。$ render(); } } – Sat

回答

0

你不需要ng-change。您只需觀察變量並使用$scope.$watch進行更新即可。您也可以從輸入中刪除ng-initng-value

var myApp = angular.module('myApp', []); 
 
    myApp.controller('ctrl', ['$scope', function ($scope) { 
 
     $scope.form={}; 
 
     $scope.$watch('form.field1 + form.field2', function (value) { 
 
     $scope.form.field3 = value; 
 
    }); 
 
    }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></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"/> 
 
</div>

0

我創建了ngchange功能,並張貼在那裏的計算:

<input type="number" ng-model="form.field1" /> 
    <input type="number" ng-model="form.field2" ng-change="Myfunction()" /> 
    <input type="number" ng-model="form.field3" /> 

控制器

$scope.form = { 
    field1: 0,field2: 0, field3: 0 
    }; 

    $scope.Myfunction = function() { 
    $scope.form.field3 = $scope.form.field1 + $scope.form.field2; 
    } 

Working Demo

而且我們不需要countng-initng-value現在。

+0

如果用戶在第二個輸入上鍵入,然後在第一個輸入上鍵入,該怎麼辦?你的回答沒有考慮到這一點? – Vivz

+0

這個問題本身並沒有在第一次輸入時提及'ng-change',所以我雖然只要求第二次輸入。 –

+0

如果他想要那個功能,那麼他可以在第一個輸入中添加'ng-change =「Myfunction()」'並且它會工作 –

相關問題