我在验证 AngularJS 中的自定义表单控件时遇到问题。
这两个问题是:
我想在内容可编辑字段中未修改占位符/初始文本时触发自定义错误。我尝试了各种方法——但没有运气(包括尝试编辑
$isValid
)。已解决:我似乎无法触发
ng-show
错误消息以使它们在ng-minlength
、ng-maxlength
和ng-required
无效时出现。(答案:我在 div 上没有名字 attr)
请参阅下面的 Plnkr 和代码示例:
https://plnkr.co/edit/Up6Q4D7cMDQQxCodLrpE?p=preview
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example40-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="form-example2">
<form name="myForm">
<div contentEditable="true" ng-model="standfirst" title="Click to edit" ng-required="true" ng-minlength="5" ng-maxlength="20">Some People</div>
<p ng-show="myForm.standfirst.$error.required" class="text-danger">You did not enter a standfirst</p>
<p ng-show="myForm.standfirst.$error.minlength" class="text-danger">Your standfirst is too short</p>
<p ng-show="myForm.standfirst.$error.maxlength" class="text-danger">Your standfirst is too long</p>
</form>
<pre>model = {{content}}</pre>
<style type="text/css">
div[contentEditable] {
cursor: pointer;
background-color: #D0D0D0;
}
</style>
</body>
</html>
(function(angular) {
'use strict';
angular.module('form-example2', []).directive('contenteditable', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
// view -> model
elm.on('blur', function() {
ctrl.$setViewValue(elm.html());
});
// model -> view
ctrl.$render = function() {
elm.html(ctrl.$viewValue);
};
// load init value from DOM
ctrl.$setViewValue(elm.html());
}
};
});
})(window.angular);