bryan
bryan

Reputation: 9399

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:

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.

Upvotes: 2

Views: 948

Answers (2)

falsarella
falsarella

Reputation: 12447

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>

Upvotes: 0

PSL
PSL

Reputation: 123739

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]"

Upvotes: 5

Related Questions