javascript - Word count in AngularJS -


i trying write quick program counts number of words in angularjs. textarea in html , underneath should display number of words user inputs them.

so html code:

 <!doctype html>  <html ng-app>  <head>     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>     <script src="wordcount.js"></script>  </head>  <body>     <div ng-controller="wordcount">         <label>copy , paste text:</label><br>         <textarea cols="80" rows="20" ng-model="mytext"></textarea>         <hr>         <span>{{wordcount()}} word(s)</span>     </div>  </body> </html> 

and here javascript file called wordcount.js (to count number of words in given string):

function wordcount($scope) {     $scope.numberofwords = function(s) {         s = document.getelementbyid("mytext").value;         s = s.replace(/(^\s*)|(\s*$)/gi,"");         s = s.replace(/[ ]{2,}/gi," ");         s = s.replace(/\n /,"\n");         return s.split(' ').length;     } } 

i found above on http://www.mediacollege.com/internet/javascript/text/count-words.html

so have not understood how use angularjs (and js code wrong too) update number of words instantly. right doesn't show "words".

does have idea?

one of correct way use $scope function:

<body ng-controller="wccontroller">     <h3>world count</h3>     <div>total words: <span ng-bind="countof(mytext)"></span></div>     <textarea ng-model="mytext"></textarea> </body> 

and @ controller:

$scope.countof = function(text) {     var s = text ? text.split(/\s+/) : 0; // splits text on space/tab/enter     return s ? s.length : ''; }; 

you can test on plunker: http://run.plnkr.co/mk9bjxiubs8hgogm/


Comments

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -