Avi Kenjale
Avi Kenjale

Reputation: 2784

angularjs create custom event directive

I have a simple attribute-restricted directive like

app.directive('akMouseOver', function () {
return {
    restrict: 'A',
    scope: {
        mouseOver: '&akMouseOver'
    },
    controller: function ($scope) {

    },
    link: function (scope, elem, attrs) {
        elem.bind('mouseover', function () {
            scope.mouseOver({ hValue: value });
        });
    }
}})

that I am calling on a simple HTML button as

<button ak-mouse-over='btnMouseOver('Win Win')' class='btn btn-primary'> Hello There !</button>

and my parent controller method is

$scope.btnMouseOver = function (hValue) {
    alert(hValue + 'Hello !!!');
}

Here, somehow, I am unable to pass a parameter to the parent method. If I make this implementation without parameter, it is working and I see alert(), if I hover the mouse over the button.

Looking for passing (a) parameter/s without adding additional attribute/directive/scope variable.

Upvotes: 1

Views: 3873

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

In your case it should work & then it would alert with Win Win Hello !!! because you had hardcoded value of function level, even if you pass value from directive it will just pass the same.

While passing value from directive to registered function of isolated scope, you should have btnMouseOver(hValue), because when you are calling mouseOver function of directive which will basically going to call btnMouseOver method registered on ak-mouse-over attribute.

At the time of passing value you need to have pass value to parent controller function in JSON kind of format like {hValue: value} where hValue will represent parameter of btnMouseOver function, placed over a ak-mouse-over and then value is value which you are passing to function.

<button ak-mouse-over="btnMouseOver(hValue)">
    Hello There !
</button>

Also you need to call scope.$apply() from mouserover event handler to keep of digest cycle as you are running an event outside angular context.

Demo here

Upvotes: 1

Related Questions