8

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';
    }
});
Langdon
  • 19,875
  • 18
  • 88
  • 107

1 Answers1

10

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})

Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • 4
    @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. – Mark Rajcok Apr 16 '13 at 17:22
  • 1
    You mean where it *was* in the docs! Saw it a few weeks ago, but it's gone now. Long live SO. – Michael Bushe Feb 25 '14 at 15:05