AngularJS issue with ng-click and 2 expressions inside, only one fires

Issue

I have an issue, in a ng-click I have 2 expressions, and only one fires.

If I use only one expression at a time, they both work, but together they dont.

One is a function, and one is a simple: button = !button ; which I use to trigger the button state.

All of this is inside a ng-repeat, so I’ll get multiple buttons, and each has to have its own state.

What I saw is that if instead of doing: button = !button which will only work alone, but not together with the function ( so ng-click= "func(); button = !button" won’t fire the second expression).

but If I declare a simple bool in the controller like this:

button: boolean;
this.button = false;

then use: ng-click= "func(); $scope.button = !$scope.button"

It will fire both expression correctly, but the issue here is that I’m using a ng-repeat, so if 10buttons get generated, when you click one, with this solution, all the 10 buttons will get triggered because they are using the same bool.

So to avoid adding a new property on my list of objects that I loop over, just for the button state, is there a simpler solution?

I don’t even understand why using a declared boolean in the controller would work, and using a simple: var = !var in the view won’t.

I tried using instead a dummy function, with just a console.log return and it works, so it has also probably something to do with my function, but yet again, why would it work with a declared bool and not with a direct expression in the view?

the function is a bit long and calls other functions inside it, so for the purpose of my question I don’t think it’s relevant posting it and making a fiddle would also be complicated as the function takes data directly from the API.

But the important thing is that the function works correctly and it’s used in multiple places in the project.

Thank you

Solution

You can try like the below code which will let you do what you are looking for, also please check this plunker for your example scenario.

Template:

<div ng-repeat="btn in buttonList">
  <button type="button" value="btn.value" ng-click="func();btn.button=!btn.button" ng-disabled="btn.button">{{btn.name}}</button>
</div>

Controller:

$scope.buttonList = [{
    name: 'World1',
    value: 1
  }, {
    name: 'World2',
    value: 2
  }, {
    name: 'World3',
    value: 3
  }, {
    name: 'World4',
    value: 4
  }, {
    name: 'World5',
    value: 5
  }, {
    name: 'World6',
    value: 6
  }, {
    name: 'World7',
    value: 7
  }, {
    name: 'World8',
    value: 8
  }];

Answered By – Immanuel Kirubaharan

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.