1

I have ng-repeat on a div that contains a button. Say the div repeats 5 times with 5 buttons. I want to disable the 2nd button when it is clicked. How can I disable the button at that index?

<div ng-repeat='thing in things'> <button ng-click='clickToDisable($index)'>button</button> </div>

Something like this. I tried ng-disabled= 'disableButton == $index but that just disables all of the buttons.

Andy Nguyen
  • 451
  • 5
  • 17

1 Answers1

1

You can pass in the $event into the click function and set the disabled attribute to true, like this:

<div ng-repeat='thing in things'>
  <button ng-click='clickToDisable($event)'>button</button>
</div>

And in the controller:

$scope.clickToDisable = function(evt) {
    evt.currentTarget.setAttribute('disabled', 'true');
}

Here is a fiddle of it working.

wimbletim
  • 103
  • 1
  • 10
  • Thank you! I am new to AngularJS. Like the `$event` and `$index` do you know if there are more I should read and learn about ? – Andy Nguyen Jan 11 '19 at 19:32
  • @AndyNguyen I think you should look into creating directives. You really shouldn't be making DOM manipulations from a controller, that's what directives are for. If you wanted to add this disable functionality to multiple places around your application, you'd have to rewrite the `clickToDisable` for each controller utilizing it. With a directive, you could throw on a custom attribute on the element you'd like to disabled and it would just work on its own. – wimbletim Jan 11 '19 at 19:44