虽然我在Angular指令中创建了以下jQuery datetimepicker插件,但该工作正常:
http://jsfiddle.net/edwardtanguay/x9oa0u6n/2 (一个指令实例,WORKS)
我当然希望能够在页面上多次调用此指令,但即使我将id设为变量,多个控件也因某些原因无法工作,我怀疑它是因为我需要使dp.change
参数值动态化,但我不确定它究竟是指什么。
http://jsfiddle.net/x9oa0u6n/4 (两个指令实例,不工作)
如何让该指令在页面上多次独立工作?
<script type="text/ng-template" id="templateCalendarPicker">
<div class='input-group date datepicker_format' id="{{dpid}}" style="width:{{width}}px">
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</script>
<div ng-controller="mainController">
<div calendar-picker width="200" date="date1" dpid="d1"></div>
<div>The first date is <b>{{date1}}</b>.</div>
</div>
<div ng-controller="mainController">
<div calendar-picker width="200" date="date2" dpid="d2"></div>
<div>The second date is <b>{{date2}}</b>.</div>
</div>
angular.module('myApp', [])
.controller('mainController', function($scope) {
$scope.date1 = '2015-09-01';
$scope.date2 = '2015-09-30';
})
.directive('calendarPicker', function() {
var controller = function ($scope) {
var vm = this;
$('#datepicker').datetimepicker({
format:'YYYY-MM-DD',
defaultDate: new Date($scope.date)
});
var elemId = '#'+$scope.dpid;
console.log(elemId);
$(document).on('dp.change', elemId, function (a) {
var selected_date = moment(a.date._d).format('YYYY-MM-DD');
$scope.date = selected_date;
$scope.$apply();
});
$scope.$on('$destroy', function() {
$('#datepicker').data("DateTimePicker").destroy();
});
};
return {
restrict: 'A',
scope: {
date : '=',
width : '@',
dpid : '@'
},
controller: controller,
controllerAs: 'vm',
bindToController: true,
templateUrl: 'templateCalendarPicker'
};
});
答案 0 :(得分:0)
<div class="form-group" show-errors>
<div class="input-group date">
<div class="input-group-content">
<input type="text" datefield name="StartDate" class="form-control" ng-model="startDate" readonly="readonly" style="cursor:pointer;" required>
</div>
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
</div>
</div>
您可以重复使用我使用的 datefield 指令。
Angular Code
angular.module('ngApp').directive('datefield', function () {
return {
restrict: 'AC',
link: function (scope, element, attrs) {
element.datepicker({ autoclose: true, todayHighlight: true });
}
}
});
此外,你不必重复两次mainController,你可以将它封装到一个并带来相同的行为,我用指令装饰任意次。