Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Word counter in angularjs

Tags:

angularjs

I'm a newbie in angular so please bear with me. I have a character counter and word counter in my textarea. My problem is that everytime I press the space, it is also being counted by getWordCounter function. How can I fix this? Thank you in advance.

HTML:

<textarea id="notesContent" type="text" class="form-control" rows="10" ng-model="notesNode.text" ng-trim="false" maxlength="5000"></textarea>

<span class="wordCount">{{getWordCounter()}}</span>
<span style="float:right">{{getCharCounter()}} / 5000</span>

JS:

$scope.getCharCounter = function() {
   return  5000 - notesNode.text.length;
}

$scope.getWordCounter = function() {
   return $.trim(notesNode.text.split(' ').length);
}
like image 484
jhedm Avatar asked Jan 10 '23 16:01

jhedm


1 Answers

It seems like you need to call 'trim' before calling split, like this:

$scope.getWordCounter = function() {
    return notesNode.text.trim().split(' ').length;
}

If you want to support multiple spaces between words, use a regular expression instead:

$scope.getWordCounter = function() {
    return notesNode.text.trim().split(/\s+/).length;
}

Filter implementation

You can also implement wordCounter as a filter, to make it reusable among different views:

myApp.filter('wordCounter', function () {
    return function (value) {
        if (value && (typeof value === 'string')) {
            return value.trim().split(/\s+/).length;
        } else {
            return 0;
        }
    };
});

Then, in the view, use it like this:

<span class="wordCount">{{notesNode.text|wordCounter}</span>

See Example on JSFiddle

like image 76
urish Avatar answered Jan 22 '23 21:01

urish