Ankur Aggarwal Ankur Aggarwal - 11 days ago 7
AngularJS Question

Disable and Enable Hover in AngularJS

I want to enable and disable hover state on element on some condition. Very new to angular so don't know how to approach towards it. Also didn't find a solution on web.

Dummy CSS Code:

xyz{
background:#2f9bdb;
}

xyz:hover{
background:#d7d7d7;
}


HTML:

<button ng-click="toggleEnable()"></button>
<div class="xyz" on-hover-select></div>


ng-app and ng-module done. My JS:

angular.module('myModule',[])
.controller('myCtrl',function($scope){
$scope.enableHover=true;
$scope.toggleEnable=function(){
return $scope.enableHover=!$scope.enableHover;
}

}).directive('onHoverSelect',function(){
return{
restrict:'A',
link:function(scope,ele,attrs){
if(scope.enableHover){
//enable hover
}else{
//disable hover
}
}
}

});


I have tried using bind unbind on off on angular element but its not working. Also will directive update itself on enableHover value change? Might be basic one but very new to the framework. Please help

Answer

I like the answer from @Mephiztopheles, but it does have it's limitations and risks. First, if you need support for IE<11, pointer-events is out. Second, as pointed out, this will remove all mouse events including click.

I suggest instead that you change your CSS and add a separate class with the hover, then you can just toggle that class. You can even use the built in ngClass directive to do it.

angular.module('demo', []).controller('MainCtrl', ['$scope', function($scope){
  $scope.hoverme = true;
}]);
.box {
  height: 100px;
  width: 100px;
  background-color: teal;
  -webkit-transition: all .5s linear;
}

.hover:hover {
  background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>

<div ng-app="demo" ng-controller="MainCtrl">
  <div class="box" ng-class="{hover: hoverme}"></div>
  <button ng-click="hoverme = !hoverme">Toggle Hover</button>
</div>