在互联网上搜索了一段时间并阅读了有关 ui-grid 事件的信息后,我编写了一个指令来使用scope
实体和 ui-grid 事件在单击单元格时应用验证。
基本技巧是使用自定义可编辑模板并在其字段上应用验证。
这是代码,也可以在我的存储库中找到
(function(module){
module.directive('gridValidation', gridValidationFn);
gridValidationFn.$inject = ['uiGridEditConstants'];
function gridValidationFn(uiGridEditConstants) {
var directive = {
restrict: 'A',
template: '<div><input type="text" ng-model="txtValue" ng-change="changeTxt(txtValue)"/></div>',
scope: true,
link: gridValidationLinkFn
};
return directive;
function gridValidationLinkFn(scope, elm, attr) {
var oldTxt = scope.row.entity[scope.col.field];
scope.limit = attr.limit;
scope.txtValue = oldTxt;
function windowClickListener(ev) {
if (ev.target.nodeName !== "INPUT")
scope.editDone();
}
scope.changeTxt = function (val) {
if (attr.words) {
if (scope.txtValue && scope.txtValue.match(/\S+/g) && scope.txtValue.match(/\S+/g).length > Number(scope.limit)) {
scope.txtValue = scope.txtValue.split(/\s+/, Number(scope.limit)).join(" ");
scope.row.entity[scope.col.field] = scope.txtValue.split(/\s+/, Number(scope.limit)).join(" ");
}
else
scope.row.entity[scope.col.field] = scope.txtValue;
}
else {
if (scope.txtValue && scope.txtValue.length > Number(scope.limit)) {
scope.txtValue = scope.txtValue.slice(0, Number(scope.limit));
scope.row.entity[scope.col.field] = scope.txtValue;
}
else
scope.row.entity[scope.col.field] = scope.txtValue;
}
};
scope.editDone = function () {
scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
};
scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function () {
angular.element(window).on('click', windowClickListener);
});
scope.$on('$destroy', function () {
angular.element(window).off('click', windowClickListener);
});
}
}
}(angular.module("ModuleName")));
它对我很有效。希望它可以帮助别人