Search code examples
javascriptangularjstogglenot-operator

Toggle with ! operator not working on page load JavaScript


I have an onClick (using angular.js ng-click) where i have to toggle color of a table row with on click.

This is the initial implementation.

   <tr>
        <td ng-class="{'setType': types.isTypeSet('TYPE') == true}" ng-click="types.setType('TYPE')">

            <img class="typebox-img" src="">
            <div class="typebox">TYPE</div>

        </td>
    </tr>

where 'type' is the type of table row and 'types' is the angular controller.

types.setType(type):

 ...
 this.types[type] = ! this.types[type];
 ...

while this toggles values from the second click on, it doesnt change the value on the first click. I implemented the functionality using the if-else statement, but cant figure out why this wont work as it is a pretty basic thing to do.

this.types[type] is set to false as default.

Could someone explain why is this happening..


Solution

  • It doesn't surprise me that this doesn't work:

    ng-click='types.setType('type')
    

    Use " for the inner quotes to make the parser understand what you're trying to do (or the other way around):

    ng-click='types.setType("type")'
    

    Incidentally, you don't need a function to do this. Just initialize in your controller a bool:

    $scope.toggle = true
    

    And use in your view like this:

    ng-click='toggle = !toggle'