angularjs - 汇总 Controller 中包含的所有项目

标签 angularjs

我刚刚开始使用 AngularJS。我需要从 AngularJS 的书中升级这个购物车示例,以便所有 (items.price*item.quantity) 的总数显示在页面底部。实现它的推荐方法是什么?

<HTML ng-app>
    <head>
        <script src="js/angular.min.js"></script>
        <script>
            function CartController($scope) {
                $scope.items = [{
                    title: 'Paint pots',
                    quantity: 8,
                    price: 3.95
                },
                {
                    title: 'Pebbles',
                    quantity: 5,
                    price: 6.95
                }];

                $scope.remove = function(index) {
                    $scope.items.splice(index, 1);
                }
            }
        </script>
    </head>
    <body ng-controller='CartController'>
        <div ng-repeat='item in items'>
            <span>{{item.title}}</span>
            <input ng-model='item.quantity'>
            <span>{{item.price}}</span>
            <span>{{item.price * item.quantity}}</span>
            <button ng-click="remove($index)">Remove</button>
        </div>
    </body>
</html>

谢谢!

最佳答案

这是一个plunker :

创建一个像这样迭代所有项目的函数:

$scope.sum = function(){
  return $scope.items.reduce(function(p,item){
    return p + (item.quantity * item.price)
  },0)
}

标记:

<span>Sum : {{ sum() }}</span>

阅读更多关于 reduce method 的信息

关于angularjs - 汇总 Controller 中包含的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21208341/

相关文章:

javascript - Angular : Add class after page load

javascript - 添加 Angular-leaflet-directive 后 Grunt 构建失败

javascript - AngularJS:ng-repeat 为按钮分配不同的值;如何在按下时将值提取到js?

jquery - Angularjs。当我使用 bootstrap-select 进行 css 选择输入时如何处理 ng-click 事件

javascript - 在 Angular JS 中从 Controller 渲染已编译的模板

angularjs - 使用 Laravel 将部分 html 模板加载到 Angular 应用程序中

javascript - AngularJS服务编写风格

javascript - 如何在angularjs中向div添加元素?

javascript - ng-form 提交了一个空对象,但应该修改对象

css - AngularJS 向下滚动初始