javascript Angular.js:如何使用 ng-bind 显示 concat。数组元素作为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18679223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular.js: How do I use ng-bind to display concat. elements of an array as a string?
提问by damienstanton
I am new to Angular and have a basic question about ng-bind that I couldn't find in the documentation. My scenario is based the shopping cart app in the O'Reily Angular.js book and I cannot seem to get ng-bind to work.
我是 Angular 的新手,有一个关于 ng-bind 的基本问题,我在文档中找不到。我的场景基于 O'Reily Angular.js 书中的购物车应用程序,我似乎无法让 ng-bind 工作。
Desired output:I need to modify my controller function so I can show my updated $scope.items array elements in a 'Grand Total' span.
所需的输出:我需要修改我的控制器函数,以便我可以在“总计”跨度中显示我更新的 $scope.items 数组元素。
Here is the function:
这是函数:
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}
];
};
}
回答by Langdon
I would recommend making a grandTotal
function on your $scope
and then binding that, like this:
我建议grandTotal
在您的上创建一个函数$scope
,然后将其绑定,如下所示:
HTML
HTML
<div ng-app ng-controller="CartController">
Grand Total: <span>{{grandTotal()}}</span>
<br/>
Grand Total: <span ng-bind="grandTotal()"></span>
<br/>
</div>
JavaScript
JavaScript
$scope.grandTotal = function () {
return $scope.items.reduce(function (p, c) {
return p.price || p + c.price;
});
};
You can also use interpolation (instead of ngBind
) as indicated in the first span.
您还可以使用插值(而不是ngBind
),如第一个跨度所示。