title: Word count in AngularJS
body: <p>I am trying to write a quick program that counts the number of words in AngularJS. Basically a textarea in HTML and underneath it should display the number of words as the user inputs them.</p>
  
  <p>So this is my HTML code:</p>
  
  <pre><code> &lt;!doctype html&gt;
   &lt;html ng-app&gt;
   &lt;head&gt;
      &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"&gt;&lt;/script&gt;
      &lt;script src="wordcount.js"&gt;&lt;/script&gt;
   &lt;/head&gt;
   &lt;body&gt;
      &lt;div ng-controller="wordCount"&gt;
          &lt;label&gt;Copy and Paste your text:&lt;/label&gt;&lt;br&gt;
          &lt;textarea cols="80" rows="20" ng-model="mytext"&gt;&lt;/textarea&gt;
          &lt;hr&gt;
          &lt;span&gt;{{wordCount()}} word(s)&lt;/span&gt;
      &lt;/div&gt;
   &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>And here is my Javascript file called wordcount.js (to count the number of words in a given string):</p>
  
  <pre><code>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;
      }
  }
  </code></pre>
  
  <p>I basically found the above on <a href="http://www.mediacollege.com/internet/javascript/text/count-words.html">http://www.mediacollege.com/internet/javascript/text/count-words.html</a></p>
  
  <p>So I have probably not fully understood how to use AngularJS (and the JS code is probably wrong too) to update the number of words instantly. Right now it doesn't show anything but "words".</p>
  
  <p>Does anyone have an idea?</p>