用angularjs在循环遍历中绑定ng-model(转载---CSDN博客 )

用angularjs在循环遍历中绑定ng-model

        angularjs的双向绑定非常的好用,当修改了一个地方的值后另外一个地方也同步修改了,如果用平时的js来写的话需要写很多代码,但是用了angularjs后只需要几行代码就能轻松搞定。

        想做一个类似于淘宝的改价的功能,就是当用户拍下了宝贝后卖家给你调价的那个功能,界面就像这样:


当修改了折扣或者直接填写了优惠价格的时候折扣和优惠价格就会去计算,先看看html的代码:

<!doctype html>
<html ng-app="app">
<head>
<script src="js/angular.min.js"></script>
<script src="js/chen.js"></script>
</head>
<body ng-controller="formController">
  <table border='1' cellpadding=0 cellspacing=0>
    <tr>
      <td>商品</td>
      <td>单价</td>
      <td>数量</td>
      <td>总价</td>
      <td>优惠</td>
    </tr>
    <tr ng-repeat="a in array">
      <td>{{a.name}}</td>
      <td>{{a.price}}</td>
      <td>{{a.count}}</td>
      <td>{{a.count*a.price}}</td>
      <td><input size="1" ng-model='a.discount'
        ng-change="chanage(this)" /> 折 = <input size="1" ng-model='a.p'
        ng-change="chanage2(this)" /></td>
    </tr>
  </table>
  买家应付:  {{itemSum}}-{{preferential}}={{sum}}
  <br> 支付说明: 总价-优惠=实际支付
</body>
</html>

绑定在<input>标签上面的"a.discount"和“a.p”在controller里面的数组中并没有这两个数据,但是这么绑定了后如果你在里面填写了值就自动会在数组中创建出来

然后是angularjs的控制层:
var app = angular.module('app', []);
app.controller('formController', function($scope) {
      $scope.array = [{
            name : '小米',
            price : '20',
            count : '2'
          }, {
            name : '三星',
            price : '50',
            count : '1'
          }]; // 表格数据
      $scope.itemSum = 0; // 表格里面的总价
      $scope.preferential = 0; // 表单的优惠
      $scope.sum = 0; // 实际总价

      for (var i = 0; i < $scope.array.length; i++) {
        // 计算表单的总价
        var node = $scope.array[i];
        $scope.itemSum += (node.count * node.price);
      }

      $scope.chanage = function(t) {
        // 修改折扣后触发事件
        var node = t.a
        node.p = node.discount / 10 * node.count * node.price;// 计算折扣对应的金额
      }

      $scope.chanage2 = function(t) {
        // 修改优惠价格后对应的change事件
        var node = t.a
        var total = node.price * node.count;
        node.discount = (total - node.p) / total * 10;// 修改优惠价格后对应的折扣
      }

      $scope.$watch('array', aa, true);// 监听显示表格的数据,如果修改了就调用aa的方法

      function aa() {
        // 该方法主要是在修改了折扣或优惠后计算出新的应付的价格
        $scope.preferential = 0;
        for (var i = 0; i < $scope.array.length; i++) {
          var p = $scope.array[i].p;
          if (p != null) {
            $scope.preferential += ($scope.array[i].p - 0);
          }
        }
        $scope.sum = $scope.itemSum - $scope.preferential;
      }
    })
最后的效果:


当修改了折扣或优惠的金额后其他的地方就会同步的计算出来;

原文地址:https://www.cnblogs.com/likaixuan/p/4709036.html