我正在使用来自https://eonasdan.github.io/bootstrap-datetimepicker/的 Angular JS 1.5.0 和 Bootstrap 3 Datetimepicker
经过一段时间的努力,我终于找到了一个如何让它为我工作的解决方案:)
JSFiddle:http: //jsfiddle.net/aortega/k6ke9n2c/
HTML 代码:
<div class="form-group col-sm-4" >
<label for="birthdate" class="col-sm-4">Birthday</label>
<div class="col-sm-8">
<div class="input-group date" id="birthdate" ng-model="vm.Birthdate" date-picker>
<input type="text" class="form-control netto-input" ng-model="vm.Birthdate" date-picker-input>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<div class="form-group col-sm-4">
<label for="birthdateText" class="col-sm-4">Model:</label>
<div class="col-sm-8">
<input type="text" class="form-control netto-input" ng-model="vm.Birthdate">
</div>
</div>
</body>
应用程序.js:
只需一个控制器设置 viewmodels Birtdate 属性:
var app = angular.module('exampleApp',[]);
app.controller('ExampleCtrl', ['$scope', function($scope) {
var vm = this;
vm.Birthdate = "1988-04-21T18:25:43-05:00";
}]);
第一个指令是初始化datetimepicker并监听 dp.change 事件。
更改时 - ngModel 也会更新。
// DatePicker -> NgModel
app.directive('datePicker', function () {
return {
require: 'ngModel',
link: function (scope, element, attr, ngModel) {
$(element).datetimepicker({
locale: 'DE',
format: 'DD.MM.YYYY',
parseInputDate: function (data) {
if (data instanceof Date) {
return moment(data);
} else {
return moment(new Date(data));
}
},
maxDate: new Date()
});
$(element).on("dp.change", function (e) {
ngModel.$viewValue = e.date;
ngModel.$commitViewValue();
});
}
};
});
第二个指令是监视 ngModel,并在更改时触发输入 onChange 事件。这也将更新datetimepicker视图值。
// DatePicker Input NgModel->DatePicker
app.directive('datePickerInput', function() {
return {
require: 'ngModel',
link: function (scope, element, attr, ngModel) {
// Trigger the Input Change Event, so the Datepicker gets refreshed
scope.$watch(attr.ngModel, function (value) {
if (value) {
element.trigger("change");
}
});
}
};
});