简体   繁体   中英

Manipulating with sibling DOM elements using angularJS

Let's say we have some div with 5 img elements. On hover, I want to change the class on all elements on the left.

<div id="stars">
     <img src="star.png" data-rating="1" ng-class="{rtHover: hover}" ng-mouseover="hoveredStars($event, 1)"/>
     <img src="star.png" data-rating="2" ng-class="{rtHover: hover}" ng-mouseover="hoveredStars($event, 2)"/>
     <img src="star.png" data-rating="3" ng-class="{rtHover: hover}" ng-mouseover="hoveredStars($event, 3)"/>
     <img src="star.png" data-rating="4" ng-class="{rtHover: hover}" ng-mouseover="hoveredStars($event, 4)"/>
     <img src="star.png" data-rating="5" ng-class="{rtHover: hover}" ng-mouseover="hoveredStars($event, 5)"/>
</div>

I want on hover to change "hover" variable on sibling elements, but don't know how to access them.

$scope.hoveredStars = function ($event, $selectedRating) {
    // Handling stars
}

Accessing sibling scopes

Access with $$prevSibling and $$nextSibling properties of your scopes.


Playing with an integer

Instead of having to access siblings scopes, manipulate an integer so that ng-class directive would become something like that:

ng-class="{ rtHover: 3 < myInteger }"

Then your hoveredStar would just have to set that integer.


Performance concern

Such a rate component, if used intensively in a same page, should not be an angular component since it generates a lot of digestions from the root scope.

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