1
我为http://eonasdan.github.io/bootstrap-datetimepicker写了一个角度指令,我可以在datetimepicker上更新我的模型,但是当我尝试设置defaultDate时遇到了问题在实例化过程中使用来自我的模型的值的datetimepicker控件。在角度指令中获取模型值
这里有一个plunker:http://plnkr.co/edit/XUQSx7s0Fle2Xes77VrM?p=preview
的script.js的index.html
var app = angular.module('app', []);
app.controller('DemoCtrl', function($scope) {
$scope.modelDate = new Date("01/01/2010");
});
app.directive('datetimepicker', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
// scope.$apply(); //This fixes the issue, but throws error in console
element.datetimepicker({
defaultDate: ngModelCtrl.$modelValue
})
.on('dp.change', function(e) {
ngModelCtrl.$setViewValue(e.date);
scope.$apply();
});
}
};
});
相关部分
<div class="container">
<div class="form-group col-xs-6">
<div class="input-group date" datetimepicker ng-model="modelDate">
<input type="text" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
Date from model: {{modelDate}}
</div>
</div>
它看起来像这个问题是在当时的DateTimePicker得到实例化,模型为null。在实例化datetimepicker之前做scope.$apply()
可以解决这个问题,但是在控制台中会抛出一个错误,而这并不是解决这个问题的正确方法。任何帮助,将不胜感激!
谢谢你的提示。我将'link'函数的整个主体移到了'defer'中,它似乎在不需要'scope'的情况下工作。$ apply();'这是最好的方法吗? – Jay 2015-02-09 16:33:27
那么,你要确保''datepicker''元素已经在DOM上初始化了,然后再放置一个事件处理程序。不知道这是否是最好的方法,但这是一个可行的解决方案,不会激怒AngularJS神! (请参见[反模式](https://github.com/angular/angular.js/wiki/Anti-Patterns)) – rageandqq 2015-02-09 16:41:23