5

I'm trying to convert jQuery plugin into directive. Here is the library: Github.

In the documentation there is an option :

$(document).ready(function() {
        $("#datepicker").datepicker();
        $("#datepickerbtn").click(function(event) {
            event.preventDefault();
            $("#datepicker").focus();
        })
    });

Directive I've created :

app.directive('dateP', function(){
    return{
        restrict:'A',
        require:'ngModel',
        link:function(scope, element, attr, ngModel){
            $(element).datepicker(scope.$eval(attr.dateP));
            console.log('hey');
            ngModel.$setViewValue(scope);
        }
    }
}); 

but it's not working , any help would be appreciate it .

Plunker .

I've read this : https://amitgharat.wordpress.com/2013/02/03/an-approach-to-use-jquery-plugins-with-angularjs/

1 Answer 1

6

Basically you written ng-mode instead of ng-model and directive you should define date-picker options not the scope.$eval(attr.dateP) which is totally wrong. Inside datepicker you need to provide their options in json format like here we mentioned option as { format: 'dd/mm/yyyy' })

HTML

<input date-p id="datepicker1" class="input-small" type="text" ng-model="dt">

Directive

app.directive('dateP', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attr, ngModel) {
      element.datepicker({
        format: 'dd/mm/yyyy'
      });
    }
  }
});

Update

For show datepicker on button click you need to do add below method inside your controller.

Controller

$scope.showDatepicker =  function(){
  angular.element('#datepicker1btn').datepicker('show');
};

Working Plunkr

Thanks.

Sign up to request clarification or add additional context in comments.

4 Comments

@sani checked and plunkr and answer too
awsome , can i ask u one more thing ? how did you know that we should add this ; link: function(scope, element, attr, ngModel) { element.datepicker({ format: 'dd/mm/yyyy' });
or angular.element('#datepicker1btn').datepicker('show');
because its option for datepicker that we are providing option in json like { format: 'dd/mm/yyyy' } look at this then only it will bind to that element . bootstrap-datepicker.readthedocs.org/en/release

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.