jQuery not working with ng-repeat results

后端 未结 3 602
余生分开走
余生分开走 2020-12-14 12:33

I am using ng-repeat to build an accordion using jQuery and TB. For some reason, this is working perfectly when hardcoded but fails to trigger on click when inside of the ng

相关标签:
3条回答
  • 2020-12-14 12:44

    When we use ng-repeat and need to trigger a jquery click event just try this it worked for me.

      $(document).on("click", ".className", function() {
    
       //your code here...
    
      });
    
    0 讨论(0)
  • 2020-12-14 12:53

    The literal answer is because those handlers are bound at runtime, therefore .panel-heading doesn't exist. You need event delegation

    $(".panel").on("click", ".panel-heading", function() {
    

    Now, since you're using Angular, all DOM manipulation should be handled within a directive, not jQuery! You should be repeating either an ng-click handler, or a simple directive.

    <div class="panel-heading" toggle-collapse my-cool-directive>
    

    And the directive code:

    .directive("myCoolDirective", function() {
        return {
            restrict: "A",
            link: function(scope, elem, attrs) {
                $(elem).click(function() {
                    var target = $(elem).next(".panel-collapse");
                    target.hasClass("collapse") ? target.collapse("show") : target.collapse("hide");
                });
            }
        }
    });
    
    0 讨论(0)
  • 2020-12-14 12:54

    You can run a jquery or any other javascript code after the angular finishes its rendering. For details see this answer : https://stackoverflow.com/a/20421291/2002079

    0 讨论(0)
提交回复
热议问题