2016-08-31 104 views
2

我是角度js中的新角色。我正在使用角度創建一個小應用程序。這是我的代碼:以角度更新範圍值

<input type="text" ng-model="one" ng-change="sum()"> 
    <input type="text" ng-model="two"ng-change="sum()"> 
    <input type="text" ng-model="three"ng-change="sum()"> 
    <input type="text" ng-model="total" > 

控制器代碼:

$scope.sum = function(){ 
     $scope.total = parseInt($scope.one) + parseInt($scope.two) + parseInt($scope.three) 
    } 

所有字段的總和完美的作品。但現在我想在用戶更改總值時執行此操作,其他字段根據總字段中的值設置值。

+5

如何ü可以認爲,這三者之一應該得到當你改變你的總變化??? – Ruhul

+0

考慮以下情況:'one = 1','two = 2','three = 3',這意味着'total = 6'。如果我將總數改爲5,三個值中的哪一個會改變? 「三」可能會變成2或「2」變成1或「1」可能變成零。你如何挑選你想要改變的價值? - 基本上@Ruhul在上面的評論中說過,哈哈。 – Jorrex

回答

0

您是否期待?

 #test { 
 
    background: white; 
 
    border: 1px double #DDD; 
 
    border-radius: 5px; 
 
    box-shadow: 0 0 5px #333; 
 
    color: #666; 
 
    outline: none; 
 
    height:25px; 
 
    width: 275px; 
 
    } 
 
<!DOCTYPE html> 
 
<html> 
 

 
    <head> 
 
    <script data-require="[email protected]" data-semver="1.4.1" src="https://code.angularjs.org/1.4.1/angular.js"></script> 
 
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
 
    
 
    </head> 
 

 
    <body> 
 
    <div ng-app="myApp" ng-controller="myCtrl"> 
 
     <table> 
 
    <tr><td><b>Value1</b></td><td> <input type="text" id="test" ng-model="one" ng-change="sum()" /></td></tr> 
 
      <tr></tr> 
 

 
     <tr><td><b>Value 2</b></td><td><input id="test" type="text" ng-model="two" ng-change="sum()" /></td></tr> 
 
     <tr></tr> 
 
    <tr><td><b>Value 3</b> </td><td><input id="test" type="text" ng-model="three" ng-change="sum()" /></td></tr> 
 
    <tr></tr> 
 
     <tr><td><b>Total</b> </td><td><input id="test" type="number" ng-model="total" ng-change="newsum()"/> </td></tr> 
 
     </table> 
 
     </div> 
 
    <script> 
 
var app = angular.module('myApp', []); 
 
app.controller('myCtrl', function($scope) { 
 
    $scope.sum = function(){ 
 
     $scope.total = parseInt($scope.one) + parseInt($scope.two) + parseInt($scope.three) 
 
    } 
 
    $scope.newsum = function(){ 
 
    if($scope.total){ 
 
    var div=$scope.total/3; 
 
    var mod=$scope.total%3; 
 

 
    if(mod==0){ 
 
     $scope.one=div; 
 
     $scope.two=div; 
 
     $scope.three=div; 
 

 
    } 
 
    else{ 
 
\t var str=''+div; 
 
     var deci=parseInt(str.split(".")[0]); 
 
\t  
 
     $scope.one=deci; 
 
     $scope.two=deci; 
 
     $scope.three=deci+mod; 
 
    } 
 
    } 
 
\t else{ 
 
\t alert("Please Enter the number"); 
 
\t } 
 
\t } 
 
    
 
}); 
 
    </script> 
 
    </body> 
 

 
</html>