检查项目是否在列表中(在指令内)

时间:2016-01-06 09:40:48

标签: javascript angularjs

我有以下指令,该指令使用两个列表:listGrouplistAll。 它们是像这样的JSON对象:

$scope.usersGroup = [
  { id: '1', name: 'User 1' },
  { id: '2', name: 'User 2' },
  { id: '3', name: 'User 3' }
]

如果item中已有userGroup,我想为每个项添加一个类:

JS:

  .directive('tableList', function() {
    return {
      restrict: 'EA',
      template: '<--SOME CODE' + 
        '<tr class="ADD CLASS IF ITEM IS IN LISTGROUP" ng-repeat="item in listAll">' +
          '<th scope="row"><input type="checkbox" value="0" ng-model="item.selected"></th>' + 
          '<td><a href="#/groups/{{item.id}}">{{item.name}}</a></td>
        'MORE CODE-->',
      scope: {
        listName: "@",
        listGroup: "=",
        listAll: "=",
        submit: "&"
      },
      controller: function() {},
      link: function(scope, elem, attr, ctrl) {
        scope.checkAll = function() {
          if (scope.selectedAll) {
            scope.selectedAll = false
          } else {
            scope.selectedAll = true
          }
          angular.forEach(scope.listAll, function(item) {
            item.selected = scope.selectedAll
          })
        }
      }
    };
  })

HTML:

  <table-list
list-name="users"
list-group="usersGroup"
list-all="usersAll"
submit="submit()">
  </table-list

AngularJS的做法是什么?

3 个答案:

答案 0 :(得分:1)

我认为没有特定的角度方式。我只想在listAll中设置一个标志

link: function(scope, elem, attr, ctrl) {
        ...
        var listGroupIds = {};
        angular.forEach(scope.listGroup, function(item) {
          listGroupIds[item.id] = true;
        });
        angular.forEach(scope.listAll, function(item) {
          item.inListGroup = item.id in listGroupIds;
        });

然后在模板中

template: '<--SOME CODE' + 
        '<tr ng-class="{'myClass': item.inListGroup}" ng-repeat="item in listAll">' +
          '<th scope="row"><input type="checkbox" value="0" ng-model="item.selected"></th>' + 
          '<td><a href="#/groups/{{item.id}}">{{item.name}}</a></td>
        'MORE CODE-->',

答案 1 :(得分:1)

tr代码中使用ng-class

<tr ng-repeat="item in listAll" ng-class="getRowClass(item)">

答案 2 :(得分:0)

您甚至不需要在控制器或链接功能中编写任何内容。只需使用Array.prototype.indexOf方法,超级快捷方便:

<tr class="{selected: listGroup.indexOf(item) > -1}" ng-repeat="item in listAll">

重要提示:listGroup必须包含对listAll所拥有的相同对象的引用(无论如何它都应该如此)。