角的JS函数的基础上匹配的名称添加计数 [英] Angular js function to add counts based on match in names

查看:109
本文介绍了角的JS函数的基础上匹配的名称添加计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个 plunker

我有在格式(键,计数),默认情况下它们。

I have a text area which has some text in the format of (key,count) in them by default.

我试图实现这一目标是(在计算()函数):

What i am trying to achieve is this(in the calc() function):

在该按钮是pressed求和的结果应该显示。

When the button is pressed the results of the summation should be displayed.

我能够从文本区域分成不同的阵列分割数据,但我缺少逻辑添加时的名称相匹配。

I was able to split the data from the textarea into different arrays but i am missing the logic to add when the names match.

编辑:
请在我的plunker注意到一些更新

新建角和JavaScript!

New to angular and javascript!

推荐答案

这应该这样做。

JS: -

$scope.calc = function() {
  $scope.users = {};

   $scope.values.split('\n').forEach(function(itm){
     var person = itm.split(','),
         name,
         key;

      if(! itm.trim() || !person.length) return;

      name = person[0].trim()
      key = name.toLowerCase();

      $scope.users[key] = $scope.users[key] || {name:name, count:0};
      $scope.users[key].count += +person[1] || 0;
    });
}

HTML: -

HTML:-

<div class="alert alert-success" role="alert">
 <ul>
  <li ng-repeat="(k,user) in users">The total for {{user.name}} is {{user.count}}</li>
 </ul>
</div>

演示

Demo

添加垫片为 TRIM()的旧版浏览器。

Add shim for trim() for older browsers.

这篇关于角的JS函数的基础上匹配的名称添加计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆