计算表达式为true的数组中的项目

时间:2015-06-30 09:40:09

标签: javascript arrays angularjs angularjs-directive

我是个有角度的新手

我有一个模板的指令看起来像这样:

<div class="multiselect-styled">
    <a href="javascript:void(0);" class="link" id="link-{{ model.ControlId }}">
        <span class="options-selected" id="selected-options-{{ model.ControlId }}">TEXT</span>
        <span class="select-arrows"></span>
    </a>
</div>

我的model包含一个名为Options的数组,其中包含n个可选选项。每个选项对象都有一个布尔属性; Selected。我想用TEXT字符串替换n options selected。那么,我如何获得所选选项的数量?

当然,使用循环可以做类似这样的事情,但是在某些情况下我会直接绑定到n(使用表达式查找n)?

            var n = 0;
            angular.forEach(model.Options, function(option) {
                if (option.Selected)
                    n++;
            });

更新1

选项如下所示:

"Options": [
      {
        "Id": "ApprovedAndClosed",
        "Value": "ApprovedAndClosed",
        "Text": "ApprovedAndClosed",
        "Selected": false,
        "Code": "ApprovedAndClosed"
      },
      {
        "Id": "Cancel",
        "Value": "Cancel",
        "Text": "Cancel",
        "Selected": false,
        "Code": "Cancel"
      },
      {
        "Id": "Done",
        "Value": "Done",
        "Text": "Done",
        "Selected": false,
        "Code": "Done"
      },
      {
        "Id": "Init",
        "Value": "Init",
        "Text": "Init",
        "Selected": false,
        "Code": "Init"
      },
      {
        "Id": "ReadyForProcessing",
        "Value": "ReadyForProcessing",
        "Text": "ReadyForProcessing",
        "Selected": false,
        "Code": "ReadyForProcessing"
      },
      {
        "Id": "Rejected",
        "Value": "Rejected",
        "Text": "Rejected",
        "Selected": false,
        "Code": "Rejected"
      },
      {
        "Id": "Reminder",
        "Value": "Reminder",
        "Text": "Reminder",
        "Selected": false,
        "Code": "Reminder"
      }
]

2 个答案:

答案 0 :(得分:1)

您可以尝试使用filter

{{(model.Options | filter:{'Selected': true}).length}}

答案 1 :(得分:0)

你可以使用lodash:

AngularJs

请参阅:codepen example