0

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.

Community
  • 1
  • 1
TBE
  • 1,002
  • 1
  • 11
  • 32

1 Answers1

0

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

Community
  • 1
  • 1
Omri Aharon
  • 16,959
  • 5
  • 40
  • 58
  • 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! – TBE Oct 26 '15 at 16:28
  • 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 Oct 27 '15 at 12:39