jQuery not working with ng-repeat results

Joe Conlin picture Joe Conlin · Dec 9, 2013 · Viewed 16.7k times · Source

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!

Answer

tymeJV picture tymeJV · Dec 9, 2013

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");
            });
        }
    }
});