在AngularJS字数 [英] Word count in AngularJS

查看:128
本文介绍了在AngularJS字数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个快速程序计算的话在AngularJS数。基本上在HTML和下方一个textarea作为用户输入他们它应该显示的单词的数目。

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.

所以这是我的HTML code:

So this is my 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 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(计算给定的字符串中的字数):

And here is my Javascript file called wordcount.js (to count the number of words in a 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;
    }
}

我基本上证实了上述关于<一个href=\"http://www.mediacollege.com/internet/javascript/text/count-words.html\">http://www.mediacollege.com/internet/javascript/text/count-words.html

所以我可能没有完全理解如何使用AngularJS(和JS code可能是错的太),即时更新的字数。眼下它不显示任何东西,但字。

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".

有没有人有一个想法?

推荐答案

一个正确的方法是使用$范围功能:

One of correct way is to use a $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>

和在控制器:

$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/

You can test this on plunker: http://run.plnkr.co/Mk9BjXIUbs8hGoGm/

这篇关于在AngularJS字数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆