Jquery datepicker UI



嗨,我正在努力让这个日期/日历 Jquery UI 在 Angularjs 中工作(作为初学者)。UI小部件没有出现,我收到的错误消息是:

TypeError: elem.datepicker 不是函数

我有这个链接到jquery的

<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/cupertino/jquery-ui.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>

这是我的 html 视图:

<div ng-controller="DateCtrl">
    <h1> Date: {{date | date:"dd/MM/yyyy"}}</h1>
    <input type="text" ng-model="date" datepicker />
</div>

这是我的控制器和指令:

.controller('DateCtrl', function($scope) {
    $scope.date = new Date();
})
.directive('datepicker', function() {
    return {
        restrict: 'A',
        require : 'ngModel',
        link : function (scope, elem, attrs, ngModelCtrl) {
            elem.datepicker({
                dateFormat:'dd/mm/yy',
                onSelect: function (date) {
                    ngModelCtrl.$setViewValue(date);
                    scope.$apply();
                }
            });
        }
    }
});

我复制了您的代码,它为我工作,如下所示:

确保脚本顺序正确:

<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/cupertino/jquery-ui.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<script src="lib/angular.min.js"></script>
<script src="app.js"></script>

我的app.js

// Where 'app' is whatever you're using to define ng-app
// e.g. <body ng-app="app">
var app = angular.module('app', []);
app.controller('DateCtrl', function($scope) {
    $scope.date = new Date();
});
 app.directive('datepicker', function() {
    return {
        restrict: 'A',
        require : 'ngModel',
        link : function (scope, elem, attrs, ngModelCtrl) {
            elem.datepicker({
                dateFormat:'dd/mm/yy',
                onSelect: function (date) {
                    ngModelCtrl.$setViewValue(date);
                    scope.$apply();
                }
            });
        }
    }
});

作为另一个建议,我建议将UI Bootstrap与Angular一起使用可能更容易。

指令中需要稍作更改:

  .directive("datepicker", function () {
      return {
        restrict: "A",
        require: "ngModel",
        link: function (scope, elem, attrs, ngModelCtrl) {
          var updateModel = function (date) {
            scope.$apply(function () {
              ngModelCtrl.$setViewValue(date);
            });
          };
          var options = {
            dateFormat: "dd/mm/yy",
            onSelect: function (date) {
              updateModel(date);
            }
          };
          elem.datepicker(options);
        }
      }
    });

最新更新