4

I used this code in angular but now its limits the characters of text area but i need to limit the words. can any one help me, Thanks in advance

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

8
  • You would need to implement it yourself in JavaScript, there is nothing built-in in HTML or Angular to do it for you. You can use this answer to detect edits on your textarea; then split the contents, count the words, do something if too many. Commented Jan 13, 2016 at 7:51
  • 1
    Checkout this example: gist.github.com/scmx/cf3ab31bc5031add81da Commented Jan 13, 2016 at 8:01
  • a jsfiddle is already available on this jsfiddle.net/ksevksev/J7MJF Commented Jan 13, 2016 at 8:05
  • Why do people not understand this question, he asked to limit WORDS, he said nothing about .length or anything about characters?! Commented Jan 13, 2016 at 8:07
  • @moumit that was used to limit the character, i want for word. the character limit can be done using max-length Commented Jan 13, 2016 at 8:08

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

1 Comment

He didn't asked for the characters limit. he asked for the word limit.i just tried running the code snippet. it is limiting the characters not the words
2

* EDITED VERSION *

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>

1 Comment

I didnt asked for the characters limit. I asked for the word limit.i just tried running the code snippet. it is limiting the characters not the words
1

This would be my solution in its crudest form:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.