我也遇到了 datepicker 的这个问题,并决定添加一个默认的 jquery-ui 。实际上,您可以添加任何人。
下面的代码需要一些解释。
首先,您的模板应如下所示:
editableCellTemplate: '<input datepicker ng-model="MODEL_COL_FIELD" readonly>'
它必须包含一个ng-model 属性,其值为MODEL_COL_FIELD。此值意味着您的输入将与单元格的模型绑定。 IE。停止编辑模式后的单元格(通常是<div> 元素)将从我们的输入中获取值。 MODEL_COL_FIELD 值被ui-grid 引擎替换为模型的真实名称。在我们的例子中是row.entity['startDate']。当您阅读属性$attrs.ngModel 时,您可以看到这一点。
eval('$scope.' + $attrs.ngModel + ' = "' + value + '";');
line 出现这样的情况是因为我们不知道模型的名称。此名称由 ui-grid 引擎自动指定。代替eval,您可以创建一个函数,允许访问$scope 的值并解析$attrs.ngModel 值。
其次,当你创建一些指令时,所有的 DOM 修改都应该在 compile 部分替换。
第三,如果您在 ui-grid 中为编辑模式创建自己的指令,则必须手动触发 BEGIN_CELL_EDIT、CANCEL_CELL_EDIT 和 END_CELL_EDIT 事件(请参阅http://ui-grid.info/docs/#/tutorial/201_editable)。在我们的代码中,我们在 datepicker 的 onClose 属性中执行此操作。我们不使用onSelect,因为我们可以放松对输入的关注,日期选择器将关闭,但输入仍将打开。要停止编辑模式,我们必须触发 END_CELL_EDIT 事件:
$scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
JS代码:
var app = angular.module('app', ['ui.grid', 'ui.grid.edit']);
app.controller('MainController', function($scope) {
$scope.gridOptions = {
columnDefs: [{
name: 'startDate',
editableCellTemplate: '<input datepicker ng-model="MODEL_COL_FIELD" readonly>',
enableCellEdit: true,
width: 150
}],
data: [{
startDate: ''
}]
};
});
app.directive('datepicker', ['uiGridEditConstants', function(uiGridEditConstants) {
return {
restrict: 'A',
require: 'ngModel',
compile: function() {
return {
pre: function($scope, $elm, $attrs) {},
post: function($scope, $elm, $attrs) {
function setValueToScope(value) {
eval('$scope.' + $attrs.ngModel + ' = "' + value + '";');
$scope.$apply();
}
$elm = $($elm);
$elm.datepicker({
dateFormat: 'mm/dd/yy',
onSelect: function(date) {
setValueToScope(date);
},
onClose: function() {
$scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
}
});
$elm[0].focus();
}
};
}
};
}]);
完整代码及其工作原理可以在这里查看:http://plnkr.co/edit/NfMuGpNDqIjvoAGJ2R1B