Kevin Beal
Kevin Beal

Reputation: 10849

AngularJS - Using directives to allow jQuery click event to fire ng-click

I want to use $(selector).trigger('click') to trigger the ng-click event on that element.

I think I want to use a directive to do this, but I'm not sure how to do it. Here's kind of what I was thinking:

.directive('jClick', function() {
    return {
        restrict : 'A',
        scope: {
            'ngClick' : '&'
        },
        link: function($scope, element) {
            return element.bind('click', function(){
                $scope.ngClick({order : $scope.order});
            });
        }
    };
})

Not only does it not work, it breaks my app completely. The scenario (if it helps) is this:

I have an list of expandable zippies that expand when the function in my ng-click is called (ng-click="expand(order)").

I have a function that checks if there is a hash at the end of my current url like:

example.com#/my/route/params#83947

(I'm keeping the second hash separate from the $routeParams because they serve different purposes.)

I use a function to check if that second hash is there and scroll down the page to the corresponding list item. That all works fine, but I want it to expand that list item too hence my desire to trigger that ng-click.

Upvotes: 0

Views: 1483

Answers (1)

Ketan
Ketan

Reputation: 5891

So you want to automatically open the zippy based on a certain condition? The condition itself is not important. What you can do is tie the visibility (expand / collapse) to a boolean and set the variable on the controller. On the Zippy directive, ng-click would also set the same variable. So you have 2 ways to open and close the zippy, once through clicking the Zippy and one through setting the flag from outside.

ng-click is a built in directive not an attribute by itself or a function that you can call. I would not rely on manually triggering ng-click.

Upvotes: 2

Related Questions