【问题标题】:jQuery ui datepicker with Angularjs带有 Angularjs 的 jQuery ui 日期选择器
【发布时间】:2013-08-11 05:38:52
【问题描述】:

我想在 AngularJS 中使用 jQuery UI 日期选择器。

我有一个示例,但我的代码不起作用。

示例:

http://www.abequar.net/jquery-ui-datepicker-with-angularjs/

我的代码:

<input id="sDate" name="programStartDate" type="text" datepicker required/>



angular.module('elnApp')
 .directive('datepicker', function () {
  return {
    restrict: 'A',
    require : 'ngModel',
    link : function (scope, element, attrs, ngModelCtrl) {
        $(function(){
            element.datepicker({
                dateFormat:'yy-mm-dd',
                onSelect:function (date) {
                    ngModelCtrl.$setViewValue(date);
                    scope.$apply();

                }
            });
        });
    }
} });

它显示错误TypeError: Object [object Object] has no method 'datepicker'

【问题讨论】:

  • 试试$(element).datepicker()
  • 好的,感谢您的帮助,但我想知道为什么?你能告诉我两者有什么不同吗?
  • element 可能只是一个 jQLite 包装器,而不是功能齐全的 jQuery 对象。
  • 我遇到了同样的问题,@madhead 的解决方案解决了它。谢谢
  • 确保在 Angular 之前包含 jQuery。它将选择并使用实际的 jQuery 库而不是 jQLite。见the documentation on angular.element

标签: jquery jquery-ui angularjs


【解决方案1】:

我的代码与你和我的作品几乎完全相同。

页面中是否包含 jQueryUI.js?

有一个小提琴here

<input type="text" ng-model="date" jqdatepicker />
<br/>
{{ date }}


var datePicker = angular.module('app', []);

datePicker.directive('jqdatepicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
         link: function (scope, element, attrs, ngModelCtrl) {
            element.datepicker({
                dateFormat: 'DD, d  MM, yy',
                onSelect: function (date) {
                    scope.date = date;
                    scope.$apply();
                }
            });
        }
    };
});

您还需要在 HTML 中的某处使用 ng-app="app"

【讨论】:

  • 我应该怎么做才能在文本框旁边有一个日期选择器图标(可点击)?
  • 如果我在单个页面中使用多个日期选择器,其中每个控件都连接到不同的 ng-model,如何在 ng-model 中设置值?
  • 如何在日期字段上使用css(color, ...)?
  • 我找到了,例如:element.prop("readonly", true); element.css("背景色", "透明")
  • 这段代码的问题是你的 onSelect 正在做“scope.date = date;”因此,无论您声明哪个 $scope 变量,每当您选择日期时,它都会更新“$scope.date”中的日期值。
【解决方案2】:
angular.module('elnApp')
.directive('jqdatepicker', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ctrl) {
            $(element).datepicker({
                dateFormat: 'dd.mm.yy',
                onSelect: function(date) {
                    ctrl.$setViewValue(date);
                    ctrl.$render();
                    scope.$apply();
                }
            });
        }
    };
});

【讨论】:

  • 这个答案非常有效,即使是嵌套属性,而下面的一个可悲的是没有。
  • 这应该是正确的答案,因为在这里您还设置了视图值!谢谢
  • 如何处理多输入?
  • 如果输入字段已经包含日期,如何格式化?
【解决方案3】:

作为最佳实践,尤其是如果您有多个日期选择器,则不应硬编码元素的范围变量名称。

相反,您应该获取点击输入的ng-model 并在onSelect 方法中更新其对应的范围变量。

app.directive('jqdatepicker', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModelCtrl) {
            $(element).datepicker({
                dateFormat: 'yy-mm-dd',

                onSelect: function(date) {
                    var ngModelName = this.attributes['ng-model'].value;

                    // if value for the specified ngModel is a property of 
                    // another object on the scope
                    if (ngModelName.indexOf(".") != -1) {
                        var objAttributes = ngModelName.split(".");
                        var lastAttribute = objAttributes.pop();
                        var partialObjString = objAttributes.join(".");
                        var partialObj = eval("scope." + partialObjString);

                        partialObj[lastAttribute] = date;
                    }
                    // if value for the specified ngModel is directly on the scope
                    else {
                        scope[ngModelName] = date;
                    }
                    scope.$apply();
                }

            });
        }
    };
});

编辑

为了解决@Romain 提出的问题(嵌套元素),我修改了我的答案

【讨论】:

  • 如果ng-model 是嵌套属性,则不起作用。例如ng-model="delivery.date" 将更新作用域的"delivery.date" 属性,而不是$scope.delivery"date" 属性。
  • 虽然我解决了您描述的问题,但我刚刚意识到@vicont 的答案更好。更优雅。
【解决方案4】:

我终于能够在 Angular js 中运行 datepicker 指令了,这里有指针

依次包含以下JS

  1. jquery.js
  2. jquery-ui.js
  3. angular-min.js

我添加了以下内容

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"> </script>      

在html代码中

<body ng-app="myApp" ng-controller="myController">
// some other html code 
<input type="text" ng-model="date" mydatepicker />
<br/>
 {{ date }}
 //some other html code
 </body>

在 js 中,请确保先为指令编码,然后再为控制器添加代码,否则会导致问题。

日期选择器指令:

var app = angular.module('myApp',[]);
app.directive('mydatepicker', function () {
return {
    restrict: 'A',
    require: 'ngModel',
     link: function (scope, element, attrs, ngModelCtrl) {
        element.datepicker({
            dateFormat: 'DD, d  MM, yy',
            onSelect: function (date) {
                scope.date = date;
                scope.$apply();
            }
        });
    }
  };
});

上述答案中引用的指令代码。

在这个指令之后,写控制器

app.controller('myController',function($scope){
//controller code
};

在 Angular js 中试试这个

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>  

连同 jquery.js 和 jquery-ui.js

我们可以将 Angular js datepicker 实现为

<input type="date" ng-model="date" name="DOB">

这提供了内置的日期选择器,日期在 ng-model 中设置,可用于进一步处理和验证。

在使用以前的方法成功进行大量头部撞击后发现了这一点。 :)

【讨论】:

  • 关于 ,它是如何工作的。你有工作样本要展示吗?
【解决方案5】:

我修改了代码并在 $apply() 中包装了视图更新。

link: function (scope, elem, attrs, ngModelCtrl){   
var updateModel = function(dateText){
    // call $apply to update the model
    scope.$apply(function(){
        ngModelCtrl.$setViewValue(dateText);
    });
};
var options = {
    dateFormat: "dd/mm/yy",
     // handle jquery date change
    onSelect: function(dateText){
        updateModel(dateText);
    }
};
 // jqueryfy the element
elem.datepicker(options);

}

工作小提琴 - http://jsfiddle.net/hsfid/SrDV2/1/embedded/result/

【讨论】:

  • 嗨@hS4 我试试这个波,但得到这样的错误'选项 onSelect 无法识别!'
【解决方案6】:

onSelect 在 ng-repeat 中效果不佳,所以我使用事件绑定制作了另一个版本

html

<tr ng-repeat="product in products">
<td>
    <input type="text" ng-model="product.startDate" class="form-control date-picker" data-date-format="yyyy-mm-dd" datepicker/>
</td>
</tr>

脚本

angular.module('app', []).directive('datepicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            element.datepicker();
            element.bind('blur keyup change', function(){
                var model = attrs.ngModel;
                if (model.indexOf(".") > -1) scope[model.replace(/\.[^.]*/, "")][model.replace(/[^.]*\./, "")] = element.val();
                else scope[model] = element.val();
            });
        }
    };
});

【讨论】:

    【解决方案7】:

    不幸的是,vicont 的回答对我不起作用,所以我搜索了另一个同样优雅的解决方案,它也适用于 ng-model 中的嵌套属性。它使用 $parse 并通过链接函数中的 attrs 访问 ng-model,而不是要求它:

    myApp.directive('myDatepicker', function ($parse) {
        return function (scope, element, attrs, controller) {
          var ngModel = $parse(attrs.ngModel);
          $(function(){
            element.datepicker({
                ...
                onSelect:function (dateText, inst) {
                    scope.$apply(function(scope){
                        // Change binded variable
                        ngModel.assign(scope, dateText);
                    });
                }
            });
         });
        } 
    });
    

    来源:ANGULAR.JS BINDING TO JQUERY UI (DATEPICKER EXAMPLE)

    【讨论】:

      【解决方案8】:

      Angular 的主 Index.html 文件可以使用 body 标签作为 ng-view。然后,您需要做的就是在 Angular 将任何页面拉入 Index.html 的底部包含一个脚本标记,如下所示:

      <script type="text/javascript">
      $( function() {
          $( "#mydatepickerid" ).datepicker({changeMonth: true, changeYear: true, 
              yearRange: '1930:'+new Date().getFullYear(), dateFormat: "yy-mm-dd"});
      });
      </script>
      

      为什么要把事情复杂化??

      【讨论】:

        【解决方案9】:

        这是我的代码-

        var datePicker = angular.module('appointmentApp', []);
        
        datePicker.directive('datepicker', function () {
            return {
                restrict: 'A',
                require: 'ngModel',
                 link: function (scope, element, attrs, ngModelCtrl) {
                    $(element).datepicker({
                        dateFormat: 'dd-mm-yy',
                        onSelect: function (date) {
                            scope.appoitmentScheduleDate = date;
                            scope.$apply();
                        }
                    });
                }
            };
        });
        

        【讨论】:

          【解决方案10】:
          myModule.directive('jqdatepicker', function () {
              return {
                  restrict: 'A',
                  require: 'ngModel',
                   link: function (scope, element, attrs, ngModelCtrl) {
                      element.datepicker({
                          dateFormat: 'dd/mm/yy',
                          onSelect: function (date) {   
                              var ar=date.split("/");
                              date=new Date(ar[2]+"-"+ar[1]+"-"+ar[0]);
                              ngModelCtrl.$setViewValue(date.getTime());
                          //    scope.course.launchDate = date;
                              scope.$apply();
                          }
                      });
          
                  }
              };
          });
          

          HTML 代码:

          <input type="text" jqdatepicker  ng-model="course.launchDate" required readonly />
          

          【讨论】:

          • 在 StackOverflow 中,我们不希望只使用一些代码作为答案,而是将其与解释放在一起。how-to-answer。此外,您应该正确缩进。
          【解决方案11】:
          var selectDate = element.datepicker({
              dateFormat:'dd/mm/yy',
              onSelect:function (date) {
                  ngModelCtrl.$setViewValue(date);
                  scope.$apply();
              }
          }).on('changeDate', function(ev) {
              selectDate.hide();
              ngModelCtrl.$setViewValue(element.val());
              scope.$apply();
          });                            
          

          【讨论】:

          • 虽然代码可能是正确的,但一点点文字会对其他人有所帮助。
          【解决方案12】:

          我遇到了同样的问题,通过按顺序放置引用和包含解决了这个问题:

          <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
          <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
          <link href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" rel="stylesheet"/>
          <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
          

          var datePicker = angular.module('app', []);
          
          datePicker.directive('jqdatepicker', function () {
              return {
                  restrict: 'A',
                  require: 'ngModel',
                   link: function (scope, element, attrs, ngModelCtrl) {
                      element.datepicker({
                          dateFormat: 'dd/mm/yy',
                          onSelect: function (date) {
                              scope.date = date;
                              scope.$apply();
                          }
                      });
                  }
              };
          });
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
          <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
          <link href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" rel="stylesheet"/>
          <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
          
          <body ng-app="app">
          <input type="text" ng-model="date" jqdatepicker />
          <br/>
          {{ date }}
          </body>

          【讨论】:

            【解决方案13】:

            我苦苦挣扎,找到了一个截至 2021 年 11 月 22 日有效的解决方案!

            你必须使用 js/css 的东西

            1. <script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
              
            2. <script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
              
            3. <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
              
            4. <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
              

            您的 html 代码在您的视图中

            <p>Date <input type="text" name="dateRange" id="dateRange" value="01/01/2018 - 01/15/2018" /></p>
            

            jquery 函数句柄应该在控制器的主体内,例如:

            app.controller('homeController', ['$location','$scope','$rootScope','$http','$cookies','$interval', function($location,$scope,$rootScope,$http,$cookies,$interval){
            
            // your $scope.fun=async function(){} etc all comes here
            
            //then
            
            //jquery function call
            $('#dateRange').daterangepicker({
                    startDate: moment().subtract(365,'days'),
                    endDate:moment(),
                    opens: 'left'
                }, function(start, end, label) {
                    console.log("A new date selection was made: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD'));
                    $scope.fromDateData=start.format('YYYY-MM-DD');
                    $scope.toDateData=end.format('YYYY-MM-DD');
                });
            }]);
            

            【讨论】:

              【解决方案14】:

              我认为您在模块声明中缺少 Angular ui 引导依赖项,如下所示:

              angular.module('elnApp', ['ui.bootstrap'])
              

              有关 Angular-ui-bootstrap,请参阅 doc

              【讨论】:

              • Angular ui bootrstrap 充当 jquery ui 的 datepicker 和 Angular 之间的桥梁,这可能就是你要找的东西
              猜你喜欢
              • 2012-11-17
              • 1970-01-01
              • 2023-03-16
              • 2019-10-18
              • 2018-01-21
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多