kumara
kumara

Reputation: 937

jquery date picker inside the angular directive

I need to show current date in the texbox. i am using jquery datepicker with angular directive. but current date did not display.

<input type="text" ng-model="cDate" xx/>
app.directive('xx', function () {
return {
    restrict: 'A',
    require: 'ngModel',
     link: function (scope, element, attrs, ngModelCtrl) {

        element.datepicker({
            dateFormat:'yy-mm-dd',
            setDate:'0',
                scope.$apply(function () {
                    ngModelCtrl.$setViewValue(date);
                });

            }
        });
    }
  };
});

Upvotes: 0

Views: 226

Answers (1)

Geethu Jose
Geethu Jose

Reputation: 1993

Try adding this in controller

  var date = new Date();
  $scope.cDate = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();

Rewrite your directive as

app.directive("xx", function() {

  function link(scope, element, attrs) {
    // CALL THE "datepicker()" METHOD USING THE "element" OBJECT.
    element.datepicker({
      dateFormat: "dd/mm/yy"
    });
  }

  return {
    require: 'ngModel',
    link: link
  };
});

// Module declaration
var myApp = angular.module('myApp', []);
// Controller declaration
myApp.controller('myController', ['$scope', function($scope) {
  var date = new Date();
  $scope.cDate = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
}]);

myApp.directive("xx", function() {

  function link(scope, element, attrs) {
    // CALL THE "datepicker()" METHOD USING THE "element" OBJECT.
    element.datepicker();
    element.datepicker({
      dateFormat: "dd/mm/yy",
      setDate: new Date()
    });
  }

  return {
    require: 'ngModel',
    link: link
  };
});
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
  <input type="text" ng-model="cDate" xx/>
</div>

Upvotes: 1

Related Questions