我正在尝试编写一个计算AngularJS中单词数量的快速程序。基本上HTML中的textarea及其下方应显示用户输入的单词数。
所以这是我的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>
这是我的名为wordcount.js的Javascript文件(用于计算给定字符串中的单词数):
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代码可能也是错误的)来立即更新单词数量。现在它除了“单词”之外没有任何显示。
有没有人有想法?
答案 0 :(得分: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/
答案 1 :(得分:3)
<强>解决方案强>
wordCount
更改时更新myText
媒体资源。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()
方法调用时的方式!