Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了angularjs – 如何限制角度JS中textarea中的单词大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我在角度中使用了这个代码,但现在它限制了文本区域的字符,但我需要限制单词.任何人都可以帮助我,提前谢谢

<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 – 如何限制角度JS中textarea中的单词全部内容,希望文章能够帮你解决angularjs – 如何限制角度JS中textarea中的单词所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: