gpt4 book ai didi

AngularJs:具有 contenteditable 的 HTML 表的动态行的必需字段验证和突出显示

转载 作者:行者123 更新时间:2023-12-04 12:39:11 30 4
gpt4 key购买 nike

我有一个如下的 HTML 表格:

<tbody>
<tr ng-repeat="r in targetTable.rows">
<td contenteditable="true" class=""></td>
<td contenteditable="true"
ng-repeat="column in targetTable.columns"
ng-model="r[column.id]"
ng-blur="!r.id? addNewRow(r[column.id], r): undefined">
</td>
</tr>
</tbody>

我正在使用 contenteditable 指令使单元格可编辑。
app.directive('contenteditable', ['$sce', function($sce) {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
var disable = (attrs.contenteditable === "false") || !Boolean(attrs.contenteditable);
if (!ngModel || disable) return; // do nothing if no ng-model

// Write data to the model
var read = function(value) {
var html = element.html() || (typeof value === "string" ? value : "");

// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if (attrs.stripBr && html == '<br>') {
html = '';
}
ngModel.$setViewValue(html);
};

// Specify how UI should be updated
ngModel.$render = function() {
element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
};

// Listen for change events to enable binding
element.on('blur keyup change', function() {
scope.$evalAsync(read);
});

setTimeout(function() {
read(ngModel.$modelValue); // initialize
});

}
};
}]);

您可以在此处查看 Jsfiddle: http://jsfiddle.net/u1vbeos5/144/

单击以添加列,它将添加动态列。在第 1 行开始输入,之后它将自动创建另一个动态行。

我现在想要的是为每一行添加必填字段验证,以便当有人点击保存时触发验证并突出显示所有空行。

我不确定我们该怎么做。我相信我们必须在指令末尾做一些事情来找出空行并突出显示它。

任何输入?

谢谢

最佳答案

无需更改您的指令,内置的 ng-required 已经可以使用。只需添加 form Controller 如评论中所述。如果您不添加表单 Controller ,则需要自己验证 $scope.save 上的所有字段.

添加 ng-required到您的模型:

<td contenteditable="true"
ng-repeat="column in targetTable.columns"
ng-model="r[column.id]"
ng-blur="!r.id? addNewRow(r[column.id], r): undefined"
ng-required="!$parent.$last"></td>
ng-required=$parent.$last表示如果该字段不是最后一行,则该字段是必需的(我根据您添加行的方式假设了这一点)。 Angularjs 将设置类 ng-invalidtd如果没有值,则为元素。

由于好像没有表格,添加 ng-form到表标记。或者,这可以用 form 包裹起来。标签应该达到同样的效果。
<table class="table table-bordered"
ng-form="targetTableForm"
ng-class="{submitted: targetTableSubmitted}">

保存时,检查表单是否有效并将表单标记为已提交。这将添加 submitted根据上面的标记将类添加到表中。
$scope.save = function() {   
$scope.targetTableSubmitted = true;

if ($scope.targetTableForm.$valid) {
alert('submitted');
} else {
alert('please fill table data');
}
/**
* If no form controller is defined, manually loop through all rows
* and columns to check for a value
*/
};

最后,添加 css 以突出显示表格单元格:
.table.submitted td.ng-invalid {
background-color: red;
}

如果表单无效,另一种方法是禁用保存按钮。

请注意,Name 列没有 ng-model,因此它不会绑定(bind)到任何东西,因此不会被验证。

查看更新 jsfiddle

关于AngularJs:具有 contenteditable 的 HTML 表的动态行的必需字段验证和突出显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51485838/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com