以角度更新范围值

时间:2016-08-31 07:46:41

标签: javascript angularjs

我是角度js的新手。我正在使用angular创建一个小应用程序。这是我的代码:

<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)
    }

所有字段的总和完美无缺。但是现在我想在用户更改总值时执行,然后其他字段根据总字段中的值设置值。

1 个答案:

答案 0 :(得分: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="angular.js@1.4.1" 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{
	 var str=''+div;
       var deci=parseInt(str.split(".")[0]);
	   
        $scope.one=deci;
        $scope.two=deci;
        $scope.three=deci+mod;
     }
    }
	else{
	alert("Please Enter the number");
	}
	}
 
});
    </script>
  </body>

</html>