Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

Similar to what this user is trying to acheive: manually calling click() on a button, can I pass any parameters?

I would like to do the same in angular JS. Something like: angular.element("mySelector").trigger("click",[{param1:val1}]);

and the access param1 in the triggered function: scope.toggleForm = function ($event) {alert($event.param1);}

Please note that angular.element("mySelector") returns an array of elements which i want to trigger the click event for each one of them separately.

Do you think this is possible? I guess I'm going to use $broadcast eventually but would love to hear some ideas.

share|improve this question

1 Answer 1

Ah, welcome to the wonderful world of Closures :)

You can do it like this:

Note: I wrote this example in the controller just for brevity. All DOM manipulation should be done inside directives!

    var elems = document.getElementsByClassName('test');
    angular.forEach(elems, function (elem) {
        angular.element(elem).bind('click', (function (x) {
            return function () {
                console.log(x); //prints woohoo
                alert(this.innerHTML);
            }
        })('woohoo'));
    });

Fiddle

share|improve this answer
    
I think you didn't understood my question. I wanted to ask how can i trigger a "click" event and pass the invoked function some data. With jQuery its pretty simple but i wanted to do it with angular. I eventually ended up using $broadcast and $on to handle my needs since it was the "angular" way of doing so in that case. Any way the article about Closures was AWESOME!!! so thanks for that! – Tomer Ben Ezra yesterday
    
1) I'm glad it helped. 2) I thought you wanted a way to pass parameters in the click? The 'woohoo' I wrote was an example of parameter passing, it could be anything you want. Then you have it as 'x' in the function. 3) I advise against using $on/$broadcast in the application as it pollutes the scopes. It is usually recommended to avoid using it. – Omri Aharon yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.