Loading

angularjs 动态计算平均值

 

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
        <script>
            var app = angular.module("myApp", []);
            app.controller("myCtrl", function($scope) {

                $scope.goods = [{                
                    num: 1,
                    price: 10
                }, {                      
                    num: 1,
                    price: 10 
                }, {                      
                    num: 1,
                    price: 10
                }, {                      
                    num: 1,
                    price: 10 
                }, {                     
                    num: 1,
                    price: 10 
                }, {                      
                    num: 1,
                    price: 10 
                }, {                      
                    num: 1,
                    price: 10 
                }, {                      
                    num: 1,
                    price: 10 
                }, {                      
                    num: 1,
                    price: 10 
                }, {                      
                    num: 1,
                    price: 10 
                }];         
                //总计
                        
                $scope.allPrice = 0;        
                $scope.getAllPrice = function() {        
                    var count = 0;   
                    $scope.good = $scope.goods.filter(function(e) {
                        return e.price != '' && e.price != 0 && e.price != null;
                    });
                    for(index in $scope.good) {
                        count += parseInt($scope.good[index].price);
                    }
                    $scope.allPrice = count / $scope.good.length;        
                }        
                $scope.getAllPrice();        

            });
        </script>
        <style>
            input::-webkit-outer-spin-button,
            input::-webkit-inner-spin-button {
                -webkit-appearance: none !important;
            }
        </style>

    </head>

    <body ng-app="myApp" ng-controller="myCtrl">
        <center>
            <table border="1px">
                <tr>
                    <td>价格</td>
                </tr>
                <tr ng-repeat="g in goods">
                    <td>
                        <span ng-show="g.flag">{{g.price}}</span>
                        <input ng-hide="g.flag" ng-model="g.price" ng-change="getAllPrice()" type="number" />
                    </td>
                </tr>
            </table><br /> 平均价:
            <span>{{allPrice}}</span>
        </center>
    </body>

</html>

 

posted @ 2019-03-05 13:37  WeiYongZhi  阅读(256)  评论(0编辑  收藏  举报