我想写一个快速程序来计算 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.mytext
。 - Mike Cofoed$scope.mytext
。从DOM中获取元素是昂贵的,并且Angular背后的整个哲学是您不应该这样做。使用模型而不是视图。 - Ayush