最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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.

Desired output: I need to modify my controller function so I can show my updated $scope.items array elements in a 'Grand Total' span.

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}
    ];

    };
} 

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.

Desired output: I need to modify my controller function so I can show my updated $scope.items array elements in a 'Grand Total' span.

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}
    ];

    };
} 
Share Improve this question edited Dec 17, 2015 at 12:36 Subodh Ghulaxe 18.7k15 gold badges86 silver badges103 bronze badges asked Sep 8, 2013 at 0:31 damienstantondamienstanton 4093 gold badges6 silver badges10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

I would remend making a grandTotal function on your $scope and then binding that, like this:

http://jsfiddle/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;
    });
};

You can also use interpolation (instead of ngBind) as indicated in the first span.

发布评论

评论列表(0)

  1. 暂无评论