gpt4 book ai didi

javascript - 在 textarea 字段上实现 maxlength 的真正 "Angularesque"方法是什么?

转载 作者:搜寻专家 更新时间:2023-10-31 23:03:09 24 4
gpt4 key购买 nike

我正在编写指令以在文本区域字段(HTML 版本 < 5)上强制执行最大长度。我正在使用 AngularJS。因此,我想以正确的 AngularJS 方式完成它。然而,当我按照我的理解去做“Angularesque”时,我无法完全让它发挥作用。

(function () {
'use strict';
var myAppModule = angular.module('myApp', []);
myAppModule.controller('MyController', function($scope) {
$scope.textareaText = "";
});

myAppModule.directive('myMaxlength', ['$compile', '$log', function($compile, $log) {
return {
priority: 10000,
restrict: 'A',
require: 'ngModel',
compile: function (elem, attrs) {
elem.attr("ng-trim", "false");
return function(scope, linkElem, linkAttrs, ctrl) {
var maxlength = parseInt(linkAttrs.myMaxlength, 10);
ctrl.$parsers.push(function (value) {
$log.info("In parser function value = [" + value + "].");
if (value.length > maxlength)
{
$log.info("The value [" + value + "] is too long!");
value = value.substr(0, maxlength);
ctrl.$setViewValue(value);
ctrl.$render();
$log.info("The value is now truncated as [" + value + "].");
}
return value;
});
};
}
};
}]);
})();

这几乎可以工作(请参阅 JSFIDDLE here 注意:此 fiddle 已经使用下面选择的解决方案进行了更新,但上面的代码仍然存在此处提到的问题。)。它正确地限制了进入模型的字符,并将其渲染回显示器。但是,您可以继续输入空格以超过指定的最大长度。多余的空间不会进入模型,但会使显示变得困惑。我相信这与 ng-trim 有关。如您所见(在代码片段中),我在编译函数中设置属性,但为时已晚。有些人建议在你的编译函数中手动调用编译来强制 AngularJS 识别动态添加的属性,但是“出现”创建另一个副本并且没有解决显示问题。将 ng-trim="false" 放在 textarea 元素上是可行的,但我想要一个干净的解决方案,用户需要做的就是添加一个指定最大长度的属性。

这是另一个例子(参见 JSFIDDLE here),在我看来它并不像“Angularesque”,但完成了工作。

(function () {
'use strict';
var myAppModule = angular.module('myApp', []);
myAppModule.controller('MyController', function($scope) {
$scope.textareaText = true;
});
myAppModule.directive('myMaxlength', ['$log', function($log) {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
var maxlength = parseInt(attrs.myMaxlength, 10);
$log.info("maxlength=[" + maxlength + "]");
elem.bind('keydown', function (event) {
$log.info("elem.val().length=[" + elem.val().length + "]");

if (elem.val().length >= maxlength)
{
// Void event Except backspace
if (event.keyCode != 8){
event.preventDefault();
}
}
});
}
};
}]);
})();

那么,在文本区域字段上实现最大长度的真正“Angularesque”方式是什么?提前致谢!

最佳答案

您可以在 html 文件的输入字段上使用 ngMaxlength 参数(此处的文档:https://docs.angularjs.org/api/ng/directive/input)

例如

<input type="text" ng-model="myRestrictedText" ng-maxlength="10"/>

关于javascript - 在 textarea 字段上实现 maxlength 的真正 "Angularesque"方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24964871/

24 4 0
文章推荐: html - 操作系统如何选择正确的 ico/favicon 大小?
文章推荐: php - 如何实现这个: object->object->property
文章推荐: php - 我想知道如何在执行 ffmpeg 命令时获取成功或失败消息
文章推荐: css - 将图像裁剪为
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com