gpt4 book ai didi

angularjs - 如何在angular JS中限制textarea中的单词

转载 作者:行者123 更新时间:2023-12-05 00:57:20 24 4
gpt4 key购买 nike

我在 angular 中使用了这段代码,但现在它限制了文本区域的字符,但我需要限制单词。任何人都可以帮助我,提前致谢

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<textarea class="form-control" placeholder="Write description about the fact" ng-model="fact.desc.en" id="title" name="description" maxlength="200" required></textarea>

最佳答案

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

myAppModule.directive('myMaxlength', ['$compile', '$log', function($compile, $log) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
attrs.$set("ngTrim", "false");
var maxlength = parseInt(attrs.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;
});
}
};
}]);


})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="parent" ng-app="myApp">
<h1>Textarea Maxlength = 5.</h1>
<h3>Open the console to see debug info.</h3>
<label for="text">Textarea label</label>:
<textarea id="text" cols="40" rows="5" my-maxlength="5" ng-model="textareaText"></textarea>
<br/><br/>
<div>This option now works great because I'm using the $set method in the AngularJS attrs object to turn off ngTrim. Even adding spaces at the end of the string are truncated as expected.</div>
<br/><br/>
<div>Model Value=<span class="model">[{{textareaText}}]</span></div>
</div>

关于angularjs - 如何在angular JS中限制textarea中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34761066/

24 4 0
文章推荐: asp.net-core - dnx 和 dnu 不在 Ubuntu 15.10 上运行
文章推荐: javascript - 如何从 React 中的