AngularJS getting $event from a directive

26,118

You need to use this syntax inside your directive:

ng-click="cbClick({ev: $event, b:\'a\'})

With this HTML:

cb-click="test(ev, b)"

Fiddle

From the directives page, section "Directive Definition Object":

Often it's desirable to pass data from the isolated scope via an expression and to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22})

Share:
26,118
Langdon
Author by

Langdon

I thoroughly enjoy writing JavaScript and C#. AngularJS has recently stolen my <3.

Updated on July 09, 2022

Comments

  • Langdon
    Langdon almost 2 years

    Seems pretty simple, but I can't get $event to bubble up from my directive. When test gets called from cb-click, $event is undefined, but outside of a directive (via html), it's the event object.

    If I use a linking function (not included in my fiddle), I can get $event, but I can't $parse/$eval it against the right scope.

    http://jsfiddle.net/langdonx/KgcGY/

    <div ng-app="app" ng-controller="x">
        <!-- via directive -->
        <checkbox cb-model="y" cb-click="test($event, b)"></checkbox>
        <!-- via html -->
        <div><input id="c2" type="checkbox" ng-model="x" ng-click="test($event, 'a')"> <label for="c2">{{x}}</label></div> 
    </div>
    

    -

    var app = angular.module('app', []);
    
    app.directive('checkbox', function ($parse) {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                cbModel: '=',
                cbClick: '&'
            },
            template: '<div><input id="c1" type="checkbox" ng-model="cbModel" ng-click="cbClick($event, \'a\')"> <label for="c1">{{cbModel}}</label></div>'
        };
    });
    
    app.controller('x', function x($scope) {
        $scope.x = true;
        $scope.y = true;
        $scope.test = function (ev, b) {
            console.log('test called, ev is', ev, 'b is', b);
            return 'xyz';
        }
    });
    
  • Mark Rajcok
    Mark Rajcok about 11 years
    @Langdon, a working example in the docs would be more helpful though. A lot of people miss this. (I certainly didn't get it the first few times I read it.) I included the documentation reference just so people could see where it is (briefly) mentioned in the docs.
  • Michael Bushe
    Michael Bushe over 10 years
    You mean where it was in the docs! Saw it a few weeks ago, but it's gone now. Long live SO.