Search code examples
angularjsangularjs-ng-clickng-class

adding removing an ng-class on a ng-click function


I have created a an ng-clickfunction which is doing the basics i need, add an active state class click here. I seem to be have an issue, removing the active class when i want to click out of the active.

 <div ng-click="showTooltip(activeTooltip)" ng-class="{ active: activeTooltip == active }">Tooltip!</div>
<script>
var app = angular.module('myApp', []);

app.controller('IndexController', function($scope) {

 $scope.activeTooltip = 'Adam';
 $scope.active = '';

 $scope.showTooltip = function(active) {

$scope.active = active;

};

});

Does anyone know the correct way of doing this?


Solution

  • The way you have implemented it (which doesn't make much sense btw), you need to register a listener for the click event on the window object (and because we are in Angular we should use the $window service).

    Every time the window object receives the click event it should reset $scope.active to ''.
    Furthermore, when calling $scope.showTooltip(), we need to stop further propagation of the click event, so it doesn't reach the window object if it is captured by the <div> first.


    Your controller should be changed like this:

    app.controller('IndexController', function($scope, $window) {
        $scope.activeTooltip = 'Adam';
        $scope.active = '';
    
        $scope.showTooltip = function (active, evt) {
            evt.stopPropagation();   // Don't let it reach $window
            $scope.active = active;    
        };
    
        $window.addEventListener('click', function (evt) {
            $scope.$apply($scope.showTooltip.bind($scope, '', evt));
        });
    });
    

    See, also, this short demo.


    It turned out I didn't get the actual requiements, which is that the tooltip class should be toggled (added/removed) each time the user clicks on the div. So, there is no need for an event-listener on the window and the code should be modified like this:

    app.controller('IndexController', function($scope, $window) {
        $scope.activeTooltip = 'Adam';
        $scope.active = '';
    
        $scope.showTooltip = function (active) {
            $scope.active = ($scope.active === active) ? '' : active;
        };
    });
    
    <div ng-class="{active:activeTooltip===active}"
         ng-click="showTooltip(activeTooltip)">
        Tooltip!
    </div>
    

    See, also, this other short demo.