Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$emit an event when clicking on an element

Tags:

angularjs

Is there a built-in directive, like ng-click, that emits an event instead of calling a function? I want to do something like this:

HTML:

<button ng-click-emit="foo" ng-click-emit-model="model.bar">Emit foo</button>

Child controller:

$scope.model = {bar: 'baz'};

Parent controller:

$scope.$on('foo', function(event, arg) {
    console.log(arg); // prints 'baz'
});
like image 428
z0r Avatar asked Nov 20 '14 00:11

z0r


People also ask

How do you trigger an event on click?

If you just need to trigger a click event, you can omit the line that begins with for( . @Parag: Read it again. The loop is to click the same link 50 times, which is what it does.

Which event occurs when the user clicks on a form element?

The onclick event occurs when the user clicks on an element.

What is the event name that fires when a user clicks on an object?

Event Handlers and Event Listeners. When a user clicks a button or presses a key, an event is fired. These are called a click event or a keypress event, respectively.


1 Answers

I figured it out: just call the scope's $emit function directly from ng-click. So the HTML in my example would become:

<button ng-click="$emit('foo', model.bar)">Emit foo</button>

The same should work for $broadcast too.

like image 99
z0r Avatar answered Sep 18 '22 21:09

z0r