The_Questioner
The_Questioner

Reputation: 312

Angularjs: How to apply a CSS property to a single element generated by ng-repeat directive

I'm generating some div tags with the ng-repeat directive. What I'd like is that when the user hovers over one of the div tags, only that div tag will change its background. However, as it stands, when the user hovers over the tag, all the ng-repeat generated elements have the property applied to them.

Here's my code for the element:

    <div class="col-xs-12">
        <div class="row">
            <div ng-repeat="verb in verbArray | filter: filterText" class="col-xs-12 col-sm-3" 
             ng-mouseenter="changeColor(true)" ng-mouseleave="changeColor(false)"
             ng-style="highlightColor">
                {{verb.name}}<img src="{{verb.presentImage}}"/><img src="{{verb.pastImage}}"/>
            </div>
        </div>
    </div>

Here is the changeColor function in the controller

    $scope.changeColor = function(theBool) {
        if(theBool === true) {
            $scope.highlightColor = {'background-color': 'green'};
        } else if (theBool === false) {
            $scope.highlightColor = {'background-color': 'white'}; //or, whatever the original color is
        }
    };

How can I make it so that the only thing that has the changeColor function applied is the element that's being hovered over?

Thank You for the help

Edit: If I did it with CSS, would it work like this:

            <div ng-repeat="verb in verbArray | filter: filterText" class="col-xs-12 col-sm-3" 
             ng-mouseenter="changeColor(true)" ng-mouseleave="changeColor(false)"
             ng-style="highlightColor" class="classOne">
                {{verb.name}}<img src="{{verb.presentImage}}"/><img src="{{verb.pastImage}}"/>
            </div>
        </div>

CSS file

.classOne:hover {
 background-color: green;
}

Upvotes: 0

Views: 169

Answers (1)

Andrei Voicu
Andrei Voicu

Reputation: 750

You can use CSS to obtain this effect with the :hover selector (https://www.w3schools.com/cssref/sel_hover.asp)

like this:

div:hover {
    background-color:green;
}

doing this through CSS is generally faster than using Angular to do it.

Upvotes: 2

Related Questions