Reputation: 8267
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?
Upvotes: 15
Views: 53632
Reputation: 9764
The following doesn't look good, but would work (it'd create another variable $event
and pass it via ng-change
):
ng-click="$event = $event" ng-change="myCallback($event)"
Upvotes: 2
Reputation: 647
To pass in values to your controller call it using an object with keys corresponding to the receiver arguments as defined on your template.
e.g.
element
<my-element change="myFunction(value, id, event)"></my-element>
caller
{
"restrict" : ...,
"scope" : {
"change" : "&"
},
"controller" : function($scope){
this.someEventHandler = function($event){
// called here
scope.change({
"value" : "somevalue",
"id" : "someid",
"event" : $event
});
}
}
}
parent controller receiver
$scope.myFunction = function(v, i, e){
// do stuff
}
REF: Passing arguments to ngChange event call from inside directive
Upvotes: 1
Reputation: 59
You have to pass the parameter in the callback like so:
callback({parametername: value});
And you have to match the parameter name with the one declared in the HTML
In your case:
callback({$event: val})
Upvotes: 5
Reputation: 9851
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:
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);
}
}
Upvotes: 5