angular ng类将类添加到除当前类之外的所有类

angular ng-class add class to all except current

本文关键字:ng 添加 angular      更新时间:2023-09-26

我在表中有一个复选框,当我选中一个复选时,我想将禁用的类添加到所有其他复选框中,我试图使用ng类实现这一点

<td scope="row">
<input 
    type="checkbox"
    id="{{$index}}"
    ng-class="{disabled: $index != currentid}"      
    ng-click="showOptions($event,'$index')" />
</td>

内部控制器

$scope.showOptions=function($event,id){
    if($event.target.checked){    
        $scope.btns = true;
        $scope.details_tab = true;
        $scope.currentid = id;
    } 
    else {
        $scope.btns = false;
        $scope.details_tab = false;
    }
};

但是在页面加载所有复选框时使用此选项会禁用类。

调用showOptions时,$index不需要是值为'$index'的字符串。它需要是值$index:

<td scope="row">
    <input type="checkbox" 
           id="{{$index}}" 
           ng-class="{disabled: $index != currentid}" 
           ng-click="showOptions($event, $index)"/>
</td>

否则,您将比较文字值$index和整数索引(例如0)。

但是在页面加载所有复选框时使用此选项会禁用类。

这是因为在页面加载时,所有$index值都不同于currentid,而currentid是您只在单击后设置的。

你需要确保你有一个复选框:

$scope.showOptions = function ($event, id) {
    if ($event.target.checked) {
        $scope.btns = true;
        $scope.details_tab = true;
        $scope.currentid = id;
        $scope.disableCheckboxes = true; //checking a checkbox
    } else {
        $scope.btns = false;
        $scope.details_tab = false;
        $scope.disableCheckboxes = false; //unchecking a checked checkbox
    }
};

在HTML中,您需要在ng-click中考虑这一点(也不需要像其他人所说的$index上的引号):

<td scope="row">
<input 
    type="checkbox"
    id="{{$index}}"
    ng-class="{disabled: disableCheckboxes && $index != currentid}"      
    ng-click="showOptions($event,$index)" />
</td>

也许您可以在currentid上添加一个验证。只有当"currentid"中有内容并且$index不是currentid时,才添加该类。现在,您可以在页面加载时将currentid设置为undefined。

<td scope="row"><input type="checkbox" id="{{$index}}" ng-class="{disabled: $index != currentid && currentid}" ng-click="showOptions($event,'$index')"></td>