How to change the class on one div while hovering over another div with AngularJS?

戏子无情 提交于 2019-12-04 04:18:47

Change my-class to myclass (i.e. the dash causes problem).

<div ng-controller="Ctrl" ng-app>
    <div ng-class="myclass">This div will change class when one hovers over bottom DIV </div>
    <br/>
    <div class="hover-div" ng-mouseenter="myclass = 'highlight'" ng-mouseleave="myclass = 'lowlight'">HOVER OVER ME TO CHANGE THE UPPER DIV's CLASS</div>    
</div>

Updated: the reason my-class isn't allowed in the expression is because AngularJS treats the dash as minus symbol and tries to parse it that way. Apparently, it can't parse the statement my - class = 'highlight'. Unfortunately, after reading AngularJS parser code, I can't find a way to "help" it distinguish between dash and minus.

You need to remove the hyphen from my-class so it will work properly in your Controller. Other than that it looks like you have it mostly done. Here's a little snippet - I also added it as text in the div so you can see it change

Your HTML File:

<div class="{{myClass}}"> {{myClass}} </div>

     <div class="hover" style="height:50px; width:50px; border:1px solid black;" ng-mouseleave="myClass='test'" ng-mouseenter="myClass='hola'"> </div>

Controller

function Ctrl($scope){
    $scope.myClass="test";
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!