Angular.js:如何使用ng-bind来显示concat.数组的元素作为字符串

Angular.js: How do I use ng-bind to display concat. elements of an array as a string?

本文关键字:数组 元素 字符串 concat 显示 js 何使用 ng-bind Angular      更新时间:2023-09-26

我是 Angular 的新手,有一个关于 ng-bind 的基本问题,我在文档中找不到。我的场景是基于O'Reily Angular.js书中的购物车应用程序,我似乎无法让ng-bind工作。

期望的输出:我需要修改我的控制器函数,以便我可以在"总计"跨度中显示我更新的 $scope.items 数组元素。

这是函数:

 function CartController($scope) {
    $scope.items = [
      {title: 'Software', quantity: 1, price: 1399.95},
      {title: 'Data Package (1TB)', quantity: 1, price: 719.95},
      {title: 'Consulting (per hr.)', quantity: 1, price: 75.00}
    ];
    $scope.remove = function(index) {
      $scope.items.splice(index, 1);
    },
    $scope.reset = function(index) {
      $scope.items = [
      {title: 'Software', quantity: 0, price: 1399.95},
      {title: 'Data Package (1TB)', quantity: 0, price: 719.95},
      {title: 'Consulting (per hr.)', quantity: 0, price: 75.00}
    ];
    };
} 

我建议在你的$scope上创建一个grandTotal函数,然后绑定它,如下所示:

http://jsfiddle.net/XMTQC/

.HTML

<div ng-app ng-controller="CartController">
    Grand Total: <span>{{grandTotal()}}</span>
    <br/>
    Grand Total: <span ng-bind="grandTotal()"></span>
    <br/>
</div>

JavaScript

$scope.grandTotal = function () {
    return $scope.items.reduce(function (p, c) {
        return p.price || p + c.price;
    });
};

您还可以使用插值(而不是ngBind),如第一个跨度所示。