gpt4 book ai didi

javascript - AngularJS 中的字数统计

转载 作者:太空狗 更新时间:2023-10-29 15:24:57 25 4
gpt4 key购买 nike

我正在尝试编写一个快速程序来计算 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 代码也可能是错误的)来即时更新字数。现在它只显示“文字”。

有没有人有想法?

最佳答案

正确的方法之一是使用 $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>

在 Controller 处:

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

关于javascript - AngularJS 中的字数统计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22312225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com