NiBu NiBu - 3 days ago 5
AngularJS Question

ng-mousover to select ONLY the hovered element not all elements - using ng-repeat

I need to add and remove a class to an element on mouseover. The method below adds and removes classes from all elements with classname .blogOverlay and .newOverlay.

I need it to add/remove the class ONLY on the element that is being hovered over.

JS:

$scope.showReadMore = function(){
$('.blogOverlay').addClass("hidden");
$('.newOverlay').removeClass('hidden');
}
$scope.hideReadmore = function(){
$('.blogOverlay').removeClass("hidden");
$('.newOverlay').addClass('hidden');
}


HTML:

<div ng-if="!post.firstFeatured" class="col-sm-10 blog-content blogPreview" >
<a ng-click="goToPostDetail(post, $index)" >
<img class="img-responsive img-blog" ng-src="{{ post.fields.image.fields.file.url }}" width="100%" alt="" />
<div class="blogOverlay" ng-mouseover="showReadMore()" ng-mouseleave="hideReadmore()">
<h2>{{ post.fields.title }}</h2>
</div>

<div class="newOverlay hidden" ng-mouseover="showReadMore()" ng-mouseleave="hideReadmore()">
<h2>{{ post.fields.title }}</h2>
<h3>{{post.fields.date}}</h3>
<a class="btn btn-primary readmore" ng-click="goToPostDetail(post, $index)">Read More</a>
</div>
</a>
</div>

Answer

There is no need to use jquery. Just use ng-class and add a condition to show or hide that class to your post. Se snipped how content is shown or hidden with the hidden class according to property post.readMore in the controller

angular.module('myapp', [])
  .controller('foo', function($scope) {

    $scope.post = {
      readMore: true,
      fields: {
        title: 'The post title',
        date: new Date()
      }
    }

    $scope.showReadMore = function(post) {
      post.readMore = true;
    }
    $scope.hideReadmore = function(post) {
      post.readMore = false;
    }


  });
<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

  <style type="text/css">
    .hidden {
      display: none;
    }
  </style>

</head>

<body ng-app="myapp">
  <div ng-controller="foo">

    <div ng-if="!post.firstFeatured" class="col-sm-10 blog-content blogPreview" style="max-width: 400px">
      <a ng-click="goToPostDetail(post, $index)">
        <img class="img-responsive img-blog" ng-src="{{ post.fields.image.fields.file.url }}" width="100%" alt="" />

        <div class="blogOverlay" ng-class="{'hidden' : !post.readMore}" ng-mouseover="showReadMore(post)" ng-mouseleave="hideReadmore(post)">
          <h2>{{ post.fields.title }}</h2>
        </div>

        <div class="newOverlay" ng-class="{'hidden' : post.readMore}" ng-mouseleave="showReadMore(post)" ng-mouseover="hideReadmore(post)">
          <h2>{{ post.fields.title }}</h2>
          <h3>{{post.fields.date}}</h3>
          <a class="btn btn-primary readmore" ng-click="goToPostDetail(post, $index)">Read More</a>
        </div>

      </a>
    </div>

  </div>


</body>

</html>

Comments