简体   繁体   中英

Angularjs changing class on mouseenter (hover)

I have the following ng-repeat that displays a star whether or not item.default is equal to true

<div ng-repeat="item in items">
    <i class="fa" ng-class="item.default == true ? 'fa-star' : 'fa-star-o'"></i>
</div>

I am using fontawesome and I wanted to do the following:

  • If item.default == false , I wanted to remove the fa-star-o class and replace it with fa-star on a mouse hover (aka a full star if you are familiar with fontawesome).
  • If item.default == true , don't do anything.

I'm knew to angular so I'm not quite sur how to accomplish this. I know I could usually create a $scope variable but since these are multiple items we are talking about, not sure how this can be done.

Any help or guidance is appreciated.

You can use ng-mouseenter , ng-mouseleave directives.

<div ng-repeat="item in items">
    <i class="fa" 
         ng-class="{true:'fa-star' ,false: 'fa-star-o'}[item.default]"
         ng-mouseenter="item.default=true"
         ng-mouseleave="item.default=false"></i>
</div>

Since you are inside ng-repeat you could as well do:

<i class="fa" 
             ng-class="{true:'fa-star' ,false: 'fa-star-o'}[hovered]"
             ng-mouseenter="hovered=true"
             ng-mouseleave="hovered=false"></i>

With this you dont attach the property hovered on the item object instead on the child scope of ng-repeat , and for default state you could add the class fa-star-o on the element as well. If you want to make the behavior default always (when a property on the item is set to true) you could just do:

ng-class="{true:'fa-star' ,false: 'fa-star-o'}[hovered||item.default]"

You could also try this way:

<div ng-repeat="item in items" ng-init="displayStarAsSelected=[]">
    <i class="fa" 
         ng-init="displayStarAsSelected[$index]=item.default"
         ng-class="{'fa-star': displayStarAsSelected[$index], 'fa-star-o': !displayStarAsSelected[$index]}"
         ng-mouseenter="displayStarAsSelected[$index]=true"
         ng-mouseleave="displayStarAsSelected[$index]=item.default"></i>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM