角度指令内的jquery日期选择器

时间:2017-05-05 05:23:12

标签: javascript jquery angularjs

我需要在texbox中显示当前日期。我正在使用带有角度指令的jquery datepicker。但是当前日期没有显示。

<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);
                });

            }
        });
    }
  };
});

1 个答案:

答案 0 :(得分:1)

尝试在控制器中添加此功能

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

将您的指令重写为

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>