3

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!

2
  • 1
    check like this: if(attr["datepicker"] == "myOnSelectMethod" && typeof myOnSelectMethod === "function") Commented Sep 3, 2013 at 16:46
  • @Cherniv thanks! That's exactly what I was looking for. I was trying to find it in the scope before... was turning into a nightmare! Commented Sep 3, 2013 at 17:05

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.