Bootstrap DateTimePicker - 关于Angular的更改事件

时间:2016-12-30 23:11:55

标签: jquery angularjs twitter-bootstrap datetimepicker

鉴于下面的演示:

http://jsfiddle.net/ADukg/8851/

我希望每次日期更改我的控制器值都要更新。因此,每次从ng-model更改值下方的框中选择新日期时。

enter image description here

然而,在使用以下指令时,我得到上面写的错误。

app.directive('datetimepicker', function () {
    return {
        restrict: 'A',
        require : 'ngModel',
        link : function (scope, element, attrs, ngModelCtrl) {

            element.datetimepicker({

                onRender:function (date) {

                    // Triggers a digest to update your model
                    scope.$apply(function () {
                        ngModelCtrl.$setViewValue(date);
                    });

                }

            });
        }
    } 
});

如何检测Datetimepicker的Angular更改?

2 个答案:

答案 0 :(得分:3)

Bootstrap的datetimepicker插件不支持构造函数选项中的change事件,但您可以使用刚刚添加dp.change元素的datetimepicker事件到:

  element.datetimepicker({});
  element.on('dp.change', function(event) { 
    scope.$apply(function () {
      ngModelCtrl.$setViewValue(event.date.format());
    });
  })

以下是对jsfiddle的更新:
http://jsfiddle.net/dekelb/fc9kuy3x/3/

答案 1 :(得分:0)

当日期发生变化时,Eonasdan bootstrap datimepicker会触发dp.change。使用所选日期更新模型的一种方法是使用以下代码:

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

myApp.controller('mainCtrl', ['$scope', function($scope) {
  $scope.compared_date = "Compare Date";
}]);


myApp.directive('datetimepicker', function () {
  return {
    restrict: 'A',
    require : 'ngModel',
    link : function (scope, element, attrs, ngModelCtrl) {

      element.datetimepicker().on('dp.change', function(e) {
        scope.compared_date = e.date;
      });
    }
  } 
});
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>

<div ng-app="myApp" ng-controller="mainCtrl">

  <div class='input-group date' id='datetimepickerday'>
    <input datetimepicker class="form-control" ng-model="compared_date"/>
    <span class="input-group-addon">
      <span class="glyphicon glyphicon-calendar"></span>
    </span>
  </div>
  Model is: {{compared_date}}
</div>

请注意e.date是一个时刻对象。此外,eonasdan的日期时间选择器是为bootstrap / jQuery环境而生的,我认为我不应该在角度项目中使用,Angular Wrapper在官方文档中链接。