Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to ngChange event call from inside directive

I have a directive that accepts an ng-change attribute:

<radio-buttons options="optionsList" 
               ng-model="myModel" 
               ng-change="myCallback($event)"></radio-buttons>

I've defined a function in my controller, myCallback, that looks like this:

$scope.myCallback = function(e) {
    console.log("Callback from controller");   
    console.log(e);
}

The following function select exists within my radioButton directive. I need to define when the ngChange callback is executed inside my directive in the select function:

function select(scope, val) {
    if (!scope.disabled && scope.selectedValue != val) {
        scope.selectedValue = val;
        scope.model = val;

        scope.callback.call();
    }
}

The problem I am having is the argument $event in myCallback is not getting passed along when I execute myCallback inside the select function of my directive.

Fiddle: http://jsfiddle.net/dkrotts/BtrZH/7/ Updated: http://jsfiddle.net/dkrotts/BtrZH/8/

What am I doing wrong?

like image 208
Dustin Avatar asked Feb 05 '13 14:02

Dustin


1 Answers

If you want to control when your handler for the ng-change is called, I think the easiest way would be to remove the ng-change completely - you can call the controller function directly from your ng-click callback.

I think this achieves your desired functionality:

http://jsfiddle.net/BtrZH/11/

You can capture the event object from the click if required:

ng-click="select(scope, option.value, $event)"

Then you can call the controller function when desired:

function select(scope, val, $event) {
    if (!scope.disabled && scope.selectedValue != val) {
        scope.selectedValue = val;
        scope.model = val;
        scope.$parent.myCallback($event);
    }
}
like image 116
Alex Osborn Avatar answered Oct 08 '22 16:10

Alex Osborn