jQuery not working with ng-repeat results
Asked Answered
A

3

11

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-repeat directive.

I was thinking that the issue is from jQuery not binding elements loaded in after the fact. So, I figured that instead of loading the script on page load, it would be better to load the function on .success when the data is returned. Unfortunately, I cannot figure out how to make this work.

Test page: http://staging.converge.io/test-json

Controller:

    function FetchCtrl($scope, $http, $templateCache) {
        $scope.method = 'GET';
        $scope.url = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=http://www.web.com&key=AIzaSyA5_ykqZChHFiUEc6ztklj9z8i6V6g3rdc';
        $scope.key = 'AIzaSyA5_ykqZChHFiUEc6ztklj9z8i6V6g3rdc';
        $scope.strategy = 'mobile';

        $scope.fetch = function() {
            $scope.code = null;
            $scope.response = null;

            $http({method: $scope.method, url: $scope.url + '&strategy=' + $scope.strategy, cache: $templateCache}).
            success(function(data, status) {
                $scope.status = status;
                $scope.data = data;
            }).
            error(function(data, status) {
                $scope.data = data || "Request failed";
                $scope.status = status;
            });
        };

    $scope.updateModel = function(method, url) {
        $scope.method = method;
        $scope.url = url;
    };
}

HTML:

            <div class="panel-group" id="testAcc">

                <div class="panel panel-default" ng-repeat="ruleResult in data.formattedResults.ruleResults">
                    <div class="panel-heading" toggle-collapse>
                        <h4 class="panel-title">
                            <a data-toggle="collapse-next" href="">
                                {{ruleResult.localizedRuleName}}
                            </a>
                        </h4>
                    </div>
                    <div class="panel-collapse collapse">
                        <div class="panel-body">
                            <strong>Impact score</strong>: {{ruleResult.ruleImpact*10 | number:0 | orderBy:ruleImpact}}
                        </div>
                    </div>
                </div>
            </div>

jQuery (works outside of ng-repeat)

$('.panel-heading').on('click', function() {
    var $target = $(this).next('.panel-collapse');

    if ($target.hasClass('collapse'))
    {
        $target.collapse('show');
    }else{
        $target.collapse('hide');
    }
});

Thanks for any help!

Agon answered 9/12, 2013 at 22:18 Comment(0)
L
21

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");
            });
        }
    }
});
Ladin answered 9/12, 2013 at 22:24 Comment(4)
This is the answer that I was looking for although I'm new to Angular and cannot figure out how to add a custom directive into my code. From everything I have read, it would seem that I need to move everything into a module to be able to add directive like this? Is this correct? If yes, do I need to change the way that the controller is written as I see it being done in other code with modules? I would really like to learn the "right" way to do this in Angular. Again, sorry for my lack of experience here. Thx.Agon
Just declare a new file, directives.js -- include your app declaration in there var app = angular.module("your app", [dependencies here]) -- then use the directive app.directive(above code) -- include directives.js in your script markupLadin
I tried this but when I assigned a module name (ng-app="moduleName") then my controller breaks. That's I was asking if the controller needed to be changed in order to make this work.Agon
Does link: (scope, elem, attrs) need to be link: function(scope, elem, attrs)?Apace
P
8

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...

  });
Pappas answered 25/2, 2016 at 11:34 Comment(1)
Great! That was quick solution.Brick
C
0

You can run a jquery or any other javascript code after the angular finishes its rendering. For details see this answer : https://mcmap.net/q/302983/-use-angularjs-just-for-routing-purposes

Clarettaclarette answered 17/2, 2014 at 12:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.