【问题标题】:using bootstrap-datepicker with angularjs. Need to find a way to update ng-model when a date is chosen将 bootstrap-datepicker 与 angularjs 一起使用。选择日期时需要找到更新 ng-model 的方法
【发布时间】:2014-07-03 14:28:55
【问题描述】:

简而言之,我需要在使用 bootstrap-datepicker 时找到更新 ng-model 的方法。这是我为演示 http://plnkr.co/edit/nNTEM25I2xX2zRKOWbD1?p=preview 发生的事情而制作的一个 plunker。我已经尝试过四处搜索,并且相当肯定我需要使用指令将值传递给模型。在文本框中键入内容将更新选定的日期模型,但仅使用日期选择器不会执行任何操作。下面的指令看起来应该可以工作,但不幸的是它似乎没有太大的效果。

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

                    onSelect : function(date) {

                        ngModelCtrl.$setViewValue(date);

                        element.datepicker("setDate", date);

                        scope.$apply();

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

一个简单的解决方案是只使用另一个日期选择器,但不幸的是,由于限制我可以使用多少个外部库,这是我必须使用的日期选择器。任何见解将不胜感激!!!

【问题讨论】:

  • 你看过 UI-Bootstrap 吗? angular-ui.github.io/bootstrap
  • 这是我最初使用的,但日历的样式与我们的网站不匹配,并且导致在线编辑出现一些问题,因此我们将其废弃并尝试使用datepicker 附带我们用来保持简单的主题。

标签: angularjs datepicker angular-ngmodel bootstrap-datepicker


【解决方案1】:

我强烈建议使用 UI-Bootstrap 或类似的东西。

但是对于那些出于某种原因需要使用 Bootstraps 日期选择器的人来说,这里是使用您的指令的起点,有一些更改:

app.directive('datepicker', function() {
   return {
      restrict: 'A',
      require: 'ngModel',
      compile: function() {
         return {
            pre: function(scope, element, attrs, ngModelCtrl) {
               // Initialize the date-picker
               $(element).datepicker({
                  format: 'dd/mm/yyyy'
               }).on('changeDate', function(ev) {
                  // Binds the changes back to the controller
                  // I also found that event.format() returns the string
                  // I wasn't aware of that. Sure beats using the date object and formatting yourself.
                  ngModelCtrl.$setViewValue(ev.format('dd/mm/yyyy'));

                  // I HATE using $apply, but I couldn't get it to work without
                  scope.$apply();
               });
            }
         }
      }
   }
});

HTML:

<input type="text" datepicker="" ng-model="date" />

非常简单直接并且允许你重复使用,here is a working plunker

【讨论】:

  • Argh,这看起来很简单,看起来应该可以工作,但无论出于何种原因,我都无法让它在我拥有的 plunker 中工作。我可能在做一些傻事。
  • 嗯,由于某种原因,我现在甚至无法打开您的 plunker。我会继续尝试并查看它,如果我看到了什么,请告诉您。
  • 嗯,嗯,出于某种原因,您似乎需要在底部的日期选择器工作之前使用顶部的日期选择器。我剥离了我正在处理的实际页面,让它看起来很适合 plunker,但所有基本功能都在那里。
  • 我唯一看到的是您缺少class='date-picker',因此第二个日期选择器不会调用准备好的文档。我添加了它,它在加载时运行良好
  • @JDubs 让它在你的指令中工作,Here's my plunker,让我知道你的想法。我会在几分钟内更改我的答案以反映这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-30
  • 2016-04-19
  • 1970-01-01
  • 2016-03-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多