Reputation: 618
I'm pretty new to Angular and I have run into a slight problem. I have this simple datepicker directive which works
app.directive('datepicker', function() {
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel){
$(elem).datepicker({
onSelect: function(dateText){
scope.$apply(function(){
ngModel.$setViewValue(dateText);
});
}
});
}
}
});
And the html I use to call it is
<input datepicker data-ng-model="day.date" readonly/>
I would like to be able to change the onSelect function called by the datepicker – hopefully with something like this.
<input datepicker="myOnSelectMethod()" data-ng-model="day.date" readonly/>
Then the directive would look something like this
app.directive('datepicker', function() {
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel){
if(myOnSelectMethod is defined){ //how do I access myOnSelectMethod here?
$(elem).datepicker({
onSelect: myOnSelectMethod();
});
}
else{ //proceed as before
$(elem).datepicker({
onSelect: function(dateText){
scope.$apply(function(){
ngModel.$setViewValue(dateText);
});
}
});
}
}
}
});
So my question is: how do I access the new onSelect function I want to execute from my link function?
Looking through the docs and other SO questions this seems like it should be possible but I haven't been able to make it work. I've come up with an ugly workaround by using an ng-click to activate the datepicker on a given element, but I would like to learn how to make this work if possible. Thanks!
Upvotes: 3
Views: 1119
Reputation: 42166
You can check this way:
if( attr["datepicker"] == "myOnSelectMethod" &&
typeof myOnSelectMethod === "function" ){
// ...
}
Or even:
if( typeof scope[attr["datepicker"]] === "function" ){ // Instead of `scope`
// ... // may be any other object,
} // `window` for example
Upvotes: 3