You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS中ng-repeat下点击按钮禁用及切换激活状态实现方案

Got it, let's solve this problem where we need to disable a button when clicked, and switch to disabling another button (while re-enabling the previous one) when another is clicked. Here's a clean, efficient approach:

Solution for Toggle Disabling Buttons in ng-repeat

Instead of managing an array of disabled states, we can track just the index of the currently disabled button. This keeps the logic simple and avoids unnecessary array updates.

Updated HTML Code

<div ng-controller="ModalDemoCtrl">
  <button 
    ng-repeat="item in items track by $index" 
    ng-click="toggleDisable($index);" 
    ng-disabled="$index === disabledButtonIndex">
    {{item.Name}}
  </button>
</div>

Updated JavaScript Code

angular.module('yourAppName', [])
  .controller('ModalDemoCtrl', function($scope) {
    $scope.items = [
      { Name: 'apple' }, 
      { Name: 'banana' }, 
      { Name: 'carrot' }, 
      { Name: 'drumstick' }, 
      { Name: 'egg' }
    ];
    
    // Initialize with no button disabled (-1 means no match)
    $scope.disabledButtonIndex = -1;

    $scope.toggleDisable = function(index) {
      if ($scope.disabledButtonIndex === index) {
        // Clicked the already disabled button? Re-enable it
        $scope.disabledButtonIndex = -1;
      } else {
        // Clicked a new button: disable it, re-enable the previous one
        $scope.disabledButtonIndex = index;
      }
    };
  });

How It Works

  1. Initial State: disabledButtonIndex starts at -1, so no button matches the condition in ng-disabled—all buttons are active.
  2. Click an Enabled Button: The function sets disabledButtonIndex to that button's index, so ng-disabled becomes true for that button, disabling it.
  3. Click a Different Enabled Button: The function updates disabledButtonIndex to the new index. The previous disabled button now no longer matches, so it re-enables, and the new button disables.
  4. Click a Disabled Button: If you want to allow re-enabling the currently disabled button (optional), the function resets disabledButtonIndex to -1, making all buttons active again.

Optional: No Toggle Behavior

If you don't want users to re-enable a disabled button by clicking it (only allow switching to another button), modify the toggleDisable function to this:

$scope.toggleDisable = function(index) {
  // Always set to the clicked index, even if it's the same (though this does nothing)
  $scope.disabledButtonIndex = index;
};

This way, clicking the same disabled button won't change anything—only clicking a different button will switch which one is disabled.

内容的提问来源于stack exchange,提问作者Pure Rhymer Organization

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:24:09