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:
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
- Initial State:
disabledButtonIndexstarts at-1, so no button matches the condition inng-disabled—all buttons are active. - Click an Enabled Button: The function sets
disabledButtonIndexto that button's index, song-disabledbecomestruefor that button, disabling it. - Click a Different Enabled Button: The function updates
disabledButtonIndexto the new index. The previous disabled button now no longer matches, so it re-enables, and the new button disables. - Click a Disabled Button: If you want to allow re-enabling the currently disabled button (optional), the function resets
disabledButtonIndexto-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

