Rohit Jindal Rohit Jindal - 4 months ago 24
HTML Question

JQuery functions not working with ng-repeat

I am using

ng-repeat
to repeat some
divs
which show list of the records.

Issue : I want to do is that when user is clicked on the record popup should be open.
ng-repeat
is working perfectly but the issue is this that JQuery click event is not working for the element inside the
ng-repeat
.

HTML Code :

<div data-ng-controller="AlbumCtrl">
<div data-ng-repeat="z in songInfo">
<div data-ng-repeat="b in z.tracks">
<div class="border-bottom clearfix">
<ul class="social-icon">
<li class="share-popup"><a class="share-song-icon"></a>
<ul class="popup">
<li><a class="share-facebook">Facebook</a></li>
<li class="last"><a class="save">Twitter</a></li>
<div class="cancel"><a>Cancel</a></div>
</ul>
</li>
</ul>
</div>
</div>
</div>
</div>


JQuery :

$('.share-popup').click(function(e)
{
e.stopPropagation();
$(this).children().toggleClass('active');
});


The
jQuery
click event working fine when i put div outside the
ng-repeat
.

Any help will be highly appreciable. Thanks.

Answer

The problem is ng-repeat renders all the div dynamically, and you are binding jQuery event at the start, at that time share-popup class element were not rendered on DOM, thats why those event don't get attached that element. You need to write your own custom directive that will restrict on class & while class element gets rendered on DOM this directive link function will get fired & event will get attached.

Directive

app.directive('sharePopup', function(){
    return{
       restrict: 'C',
       link: function(scope, element, attrs){
          element.on('click', function(e){
              e.stopPropagation();
              element.children().toggleClass('active');
          })
       }
    }
})

Better solution would be using ng-class inside your element, that would make more sense by doing code in more angular way. Then you don't need to write any external Javascript code that will handle on UI itself.

Markup

<div class="border-bottom clearfix">
  <ul class="social-icon">
    <li class="share-popup" ng-click="b.active!=b.active; $event.stopPropagation();">
      <a class="share-song-icon" ng-class="{active: b.active}"></a>
      <ul class="popup">
        <li><a class="share-facebook">Facebook</a></li>
        <li class="last"><a class="save">Twitter</a></li>
        <div class="cancel"><a>Cancel</a></div>
      </ul>
    </li> 
  </ul>
</div>

Comments