Javascript 检查项目是否在列表中(在指令内)
我有以下使用两个列表的指令:Javascript 检查项目是否在列表中(在指令内),javascript,angularjs,Javascript,Angularjs,我有以下使用两个列表的指令:listGroup和listAll。 它们是如下所示的JSON对象: $scope.usersGroup = [ { id: '1', name: 'User 1' }, { id: '2', name: 'User 2' }, { id: '3', name: 'User 3' } ] 如果item已经在userGroup中,我想为每个项添加一个类: JS: .directive('tableList', function() { retu
listGroup
和listAll
。
它们是如下所示的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
})
}
}
};
})
<table-list
list-name="users"
list-group="usersGroup"
list-all="usersAll"
submit="submit()">
</table-list
.directive('tableList',function(){
返回{
限制:“EA”,
模板:“我认为没有特定的角度方式。我只需在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-->',
模板:'在tr
标记中使用:
<tr ng-repeat="item in listAll" ng-class="getRowClass(item)">
您甚至不需要在控制器或链接函数中写入任何内容。只需使用方法即可,超级快速方便:
<tr class="{selected: listGroup.indexOf(item) > -1}" ng-repeat="item in listAll">
重要提示:listGroup
必须包含对相同对象的引用listAll
应该是这样的.可能重复使用tr
Tag上的ng类
。如果假定listGroup和listAll中都包含相同的元素,则比较只能在id上进行。此外,这可能不会随元素数量的增加而增加,值得指出。@SimoneZandara当然,listGroup应该有相同的引用.但我相信在90%的情况下应该是这样的。不,不确定你所说的“不缩放”是什么意思-缩放完美。这是一个O(N^2)方法,我的意思是谢谢你的回答。我使用了名称
属性,但奇怪的是,没有应用该类:
我完全复制了代码中的内容。你是否将类更改为ng类?