使用串联字符串角度js过滤数组列表

时间:2018-04-05 15:57:30

标签: angularjs angular-filters angular-pipe

我正在尝试使用过滤器

过滤字符串数组
var employeeRole=['Manager', 'Employee', 'Director', 'Supervisor', 'TeamLead'];
var permittedRoles='Manager|Director';

如何在permittedRoles

中找到employeeRole中的任何一个

1 个答案:

答案 0 :(得分:0)

您可以splitting permittedRoles |执行此操作并检查结果数组中是否包含任何值(使用some)(使用employeeRole中的indexOf}。

见下面一个完整的例子:

angular
  .module('app', [])
  .controller('ctrl', function($scope) {
    $scope.employeeRole = ['Manager', 'Employee', 'Director', 'Supervisor', 'TeamLead'];
    $scope.permittedRoles = 'Manager|Director';

    $scope.check = function() {
      console.log(doCheck())
    };

    /**
     * Return `true` if any of the values in `permittedRoles` separated by `|` is contained in the array `employeeRole`, `false` otherwise.
     */
    function doCheck() {
      return $scope.permittedRoles.split('|')
        .some(
          function(role) {
            return $scope.employeeRole.indexOf(role) !== -1;
          }
        );
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="ctrl">

  <label for="permittedRoles">permittedRoles: </label>
  <input id="permittedRoles" ng-model="permittedRoles" />

  <hr/>
  <a href="#" ng-click="check()">Check (click me!)</a>
  <hr/>
  <label>employeeRole:</label>
  <br/>
  <div ng-repeat="role in employeeRole">
    {{role}}
  </div>
</div>