Angularjs 指令不适用于 jQuery UI

Angularjs Directive not working with jQuery UI

我正在努力让 jQuery UI 日期选择器在 AngularJS 1.3 指令中工作。到目前为止,我已经能够让日期选择器呈现在屏幕上,并让选定的值显示在文本框中。但是,我无法将所选值传回父控制器以在应用程序中使用。

这是我的指令代码。

angular.module("demo", []).directive('myDatepicker', function ($parse) {
   return {
      restrict: "E",
      replace: true,
      transclude: false,
      compile: function (element, attrs) {
         var modelAccessor = $parse(attrs.ngModel);
     var html = "<input type='text' id='" + attrs.id + "' >" +
        "</input>";

     var newElem = $(html);
     element.replaceWith(newElem);

     return function (scope, element, attrs, controller) {

        var processChange = function () {
           var date = new Date(element.datepicker("getDate"));

           scope.$apply(function (scope) {
              // Change bound variable
              modelAccessor.assign(scope, date);
           });
        };

        element.datepicker({
           inline: true,
           onClose: processChange,
           onSelect: processChange
        });

        scope.$watch(modelAccessor, function (val) {
           var date = new Date(val);
           element.datepicker("setDate", date);
        });

     };

  }

}; });

如果您想在应用程序中使用选定的值,请记住

the selected value to be displayed within the text box

获取input的值,里面有你的话选择的datepicker的值。

我建议阅读更多关于 AngularJS 的内容,你会发现使用 $watch 和 $apply 不推荐用于这种 "simple" 甚至 "trivial" 操作。

根据您的意见,我建议您加入angular material。他们有一个很棒的日期选择器,可用于 Angular 1.3:

Angular Material Form with Date Picker Demo