如何在角度JS中限制textarea中的单词

时间:2016-01-13 07:48:57

标签: angularjs textarea word-count

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

<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>

3 个答案:

答案 0 :(得分:2)

(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>

答案 1 :(得分:2)

*已编辑版本

angular.module('AppController', []).controller('WordController', function(){
	      var wordController = this;
		  wordController.CharacterLength = 0;
		   
		  wordController.WORDS_MAXIMUM = 10; // changeable
		  
		  wordController.WordsLength=0;
		  wordController.Text = "";
		  wordController.FontStyle={'color':'red'};
		  wordController.UpdateLengths = function($event)
		  { 
		    wordController.CharacterLength = wordController.Text.length;
			wordController.WordsLength=0;
			if(wordController.Text.length == 1 && wordController.Text[0]!=' ')
			{
				wordController.WordsLength = 1;
			}
			
			for( var i=1; i< wordController.Text.length; i++)
			{ 
				if( wordController.IsAlphabet(wordController.Text[i])  && !wordController.IsAlphabet(wordController.Text[i-1]))
				{
					wordController.WordsLength++;
					if(wordController.WordsLength == wordController.WORDS_MAXIMUM + 1)// WORDS_MAXIMUM = 10
					{
						wordController.WordsLength--;
						wordController.Text = wordController.Text.substring(0, i);
						return;
					}
				}else if (wordController.IsAlphabet(wordController.Text[i]) && wordController.IsAlphabet(wordController.Text[i-1]) )
				{
					if(wordController.WordsLength==0)
					{
						wordController.WordsLength=1;
					}
				}else if(!wordController.IsAlphabet(wordController.Text[i]) && !wordController.IsAlphabet(wordController.Text[i-1]))
				{
					continue;
				}else if(!wordController.IsAlphabet(wordController.Text[i]) && wordController.IsAlphabet(wordController.Text[i-1]))
				{
					continue;
				}
			}
		  }
		  
		  wordController.IsAlphabet = function(character)
		  {
			var numeric_char = character.charCodeAt(character);
			
			if(numeric_char>64 && numeric_char<91)// A-Z
			{
				return true;
			}
			if(numeric_char>96 && numeric_char<123)// a-z
			{
				return true;
			}
			return false;
		  }
	    });
<!DOCTYPE html>
<html ng-app="AppController">
<title> Angular-102: Counting Words in Textarea </title>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  
	
  </head>
  
<body>
 <p id="sampleText">Word Count Example</p>
  <div ng-controller="WordController as wordsController">
     <p  ng-model="wordsController.CharacterLength" >You have entered <font ng-style="wordsController.FontStyle">{{wordsController.CharacterLength}} </font>/100 characters</p>
	
	<p ng-model="wordsController.WordsLength"> You have entered <font ng-style="wordsController.FontStyle">{{wordsController.WordsLength}}</font>/10 words </p>
	
	<Textarea name="TextField" ng-model="wordsController.Text" ng-change="wordsController.UpdateLengths()" ng-trim="false" rows=5 cols=50 maxlength="100"> </textarea>
  </div>
  
</body>

</html>

答案 2 :(得分:1)

这将是我最原始形式的解决方案:

(function(angular) {
  var module = angular.module('demo', []);

  module.controller('Demo1Ctrl', function($scope) {
    $scope.max = 5;
    $scope.count = 0;
    $scope.showWarning = false;

    $scope.$watch('count', function(newValue, oldValue) {
      if (newValue >= $scope.max)
        $scope.showWarning = true;
      else
        $scope.showWarning = false;
    });
  });

  module.directive('limitWords', [
    function() {
      return function(scope, element, attrs) {
        element.bind('keyup', function() {
          scope.count = this.value.split(' ').length;

          if (scope.count > scope.max)
            this.value = this.value.slice(0, this.value.length - 1);
        });
      };
    }
  ]);
}(angular));
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="app.js"></script>
<!DOCTYPE html>
<html ng-app="demo">

<head lang="en">
  <meta charset="utf-8">
  <title>Limit word count in textarea</title>
</head>

<body>
  <div ng-controller="Demo1Ctrl">
    <textarea ng-model="myText" limit-words></textarea>
    <p ng-show="showWarning">You reached maximum word count</p>
  </div>

</body>

</html>