E
E
Eugene Zalivadnyi2015-10-24 04:02:55
Angular
Eugene Zalivadnyi, 2015-10-24 04:02:55

How to add a class when hovering over a block in Angular?

There are several tr lines:

<tr class="list">
    <td class="buy">0/10</td>
    <td><a class="buy-button">Купить</a></td>
</tr>

It is necessary that only the first one is highlighted by default (buyButtonSelected class), and when hovering over any of the rows, the highlight remains only for the one that was hovered over for the last time, while all the rest should be unlit.
In jQuery it would sound something like this:
$( document ).ready(function() {
    $('#content1 tr.list:nth-of-type(1) .buy-button').addClass('buyButtonSelected');
    $('#content1 tr.list').hover(function(){    
        $('#content1 tr.list').removeClass('buyButtonSelected');
        $(this).addClass('buyButtonSelected');
    });     
});

The project is written in Angular and there is no way to use JQuery. Does Angular have similar functionality? How to implement it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
VanKrock, 2015-10-24
@VanKrock

angular.ru/api/ng.directive:ngClass
HTML

<div ng-app>
<table ng-controller="buyCtrl">
<tr ng-repeat="product in products" ng-mouseover="productHovered($index)">
    <td >{{product.name}}</td>
    <td class="buy">{{product.count}}/10</td>
    <td><a ng-class="product.buttonCss">Купить</a></td>
</tr>
</table>
</div>

css
.red{
    color:red;
}

.green{
    color:green;
}

JavaScript
function buyCtrl($scope) {
  $scope.products = [
    {name:'Помидоры', count:1, buttonCss:"green"},
    {name:'Огурцы', count:0, buttonCss:"green"},
    {name:'Картофель', count:0, buttonCss:"green"}
  ];
    
  $scope.productHovered = function(selectedProductIndex){
      $scope.products.forEach(function(product){
          product.buttonCss = "green";
      });
      $scope.products[selectedProductIndex].buttonCss = "red";
  }
}

well, just change the buttonsCss of the product to the one you need uploaded
to JsFiddle

N
Nicholas, 2015-10-24
@healqq

I think here you can get by with a bunch of ng-mouseover and ng-class. On mouseover, we save the value of the current line in some variable, for example $scope.currentIndex (if the output is done through ng-repeat, then $index will do) . In ng-class we add a class in the case when $index is equal to currentIndex.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question