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>
mfathy00
  • 1,601
  • 1
  • 13
  • 28
Nithesh S D
  • 103
  • 2
  • 10
  • 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](http://stackoverflow.com/a/14029861/240443) to detect edits on your textarea; then split the contents, count the words, do something if too many. – Amadan Jan 13 '16 at 07:51
  • 1
    Checkout this example: https://gist.github.com/scmx/cf3ab31bc5031add81da – devqon Jan 13 '16 at 08:01
  • a jsfiddle is already available on this http://jsfiddle.net/ksevksev/J7MJF/ – Moumit Jan 13 '16 at 08:05
  • Why do people not understand this question, he asked to limit **WORDS**, he said nothing about `.length` or anything about characters?! – RiesvGeffen Jan 13 '16 at 08:07
  • @moumit that was used to limit the character, i want for word. the character limit can be done using max-length – Nithesh S D Jan 13 '16 at 08:08
  • sure @Goldenowner .. than check out this .. http://stackoverflow.com/questions/22312225/word-count-in-angularjs – Moumit Jan 13 '16 at 08:15
  • That part is easy, but the part where you make a substring form the start till the max words. – RiesvGeffen Jan 13 '16 at 08:22
  • take a look [here](http://www.codeproject.com/Tips/987317/AngularJS-Counting-Words-and-Set-Word-Limit-in-Tex) – AndreaM16 Jan 13 '16 at 08:26

3 Answers3

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>
  • 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 – Thilak Raj Jan 13 '16 at 09:19
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>
Suresh B
  • 1,658
  • 1
  • 17
  • 35
  • 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 – Nithesh S D Jan 13 '16 at 09:47
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>
Mr Goododd
  • 21
  • 1