AngularJS中的字数统计

5

我想写一个快速程序来计算 AngularJS 中单词的数量。基本上是在 HTML 中的文本区域下方,应该显示用户输入的单词数量。

这是我的 HTML 代码:

 <!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 and Paste your text:</label><br>
        <textarea cols="80" rows="20" ng-model="mytext"></textarea>
        <hr>
        <span>{{wordCount()}} word(s)</span>
    </div>
 </body>
</html>

以下是我的JavaScript文件,名为wordcount.js(用于计算给定字符串中的单词数):

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

我基本上是在http://www.mediacollege.com/internet/javascript/text/count-words.html上找到了以上内容。

所以我可能没有完全理解如何使用AngularJS(JS代码也可能是错误的)来即时更新单词数量。现在它什么都不显示,只有“单词”。

有人有什么想法吗?


1
当您想要匹配计数时,为什么要进行替换?'/\b(\w+)\b/g' s.match(regex)给出一个数组.. 可以使用.length运算符来获取匹配的数量。您也可以使用非单词字符\ S来分隔而不是边界\ b.. 这在正则表达式和w3cschool JavaScript正则表达式中有涵盖。 - alexmac
我会按照alexmac所说的去做,而且由于你的<textarea>元素没有ID,所以你应该操作$scope.mytext - Mike Cofoed
即使您在“textarea”元素上有一个ID,您也应该绝对操作$scope.mytext。从DOM中获取元素是昂贵的,并且Angular背后的整个哲学是您不应该这样做。使用模型而不是视图。 - Ayush
2个回答

13

其中一种正确的方法是使用 $scope 函数:

<body ng-controller="WCController">
    <h3>World count</h3>
    <div>total words: <span ng-bind="countOf(myText)"></span></div>
    <textarea ng-model="myText"></textarea>
</body>

并在控制器上:

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

您可以在plunker上进行测试:http://run.plnkr.co/Mk9BjXIUbs8hGoGm/


太好了!这很简单。但是你能告诉我如何限制一些字数吗? - Thilak Raj
@ThilakRaj,你可以使用单个循环来创建一个有限单词字符串:var out = ""; for(var c = 0; c < limit && c<s.length; c++) { out = (out) ? out + " " + s[c] : s[c] } - Joao Polo

3

解决方案

  • myText改变时,更新wordCount 属性。
  • 在String.prototype.match调用中使用简单的正则表达式。
  • 在模板中使用更新后的wordCount作用域属性。

代码

您的监听器应该如下所示:

$scope.$watch('myText', function(text) {
    // no text, no count
    if(!text) {
        $scope.wordCount = 0;
    } 
    // search for matches and count them
    else {
        var matches = text.match(/[^\s\n\r]+/g);
        $scope.wordCount = matches ? matches.length : 0;
    }
});

重要提示

为什么在监视器中计算数量?

为了防止在模板中使用 wordCount() 方法调用时,每个消化都计算该计数的方式!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接