我尝试使用Angular的textarea
指令为ng-repeat
元素创建行号系统。基本上,使用ng-keyup
事件,我调用函数updateLineNumbers()
来计算textarea
中的总行数,并添加到$scope
附加的行数列中{1}}如果需要的话。
angular.module('editorApp')
.controller('LineNumberController', ['$scope', function($scope){
$scope.lines = [1];
$scope.updateLineNumber = function(){
var text = $("#editor").val();
var lines = text.split(/\r|\r\n|\n/);
var count = lines.length;
console.log(count);
if(count > $scope.lines.length){
console.log("adding line...");
var len = $scope.lines.length;
var linesToAdd = count - len;
console.log("lines to add: " + linesToAdd);
for(var i = 0; i < linesToAdd; i++){
console.log('adding line number: ' + (i + $scope.lines[len - 1] + 1));
$scope.lines.push(i + $scope.lines[len - 1] + 1);
}
}
}
}]);
控制台日志语句仅用于调试目的btw。这工作正常,一切都显示我想要它,但我注意到它只是稍微慢。新行号出现在光标后面片刻,使其到达下一行。我知道它挑剔,但这困扰我,我想知道在Angular中是否有解决方案,或者我应该只使用JQuery。
这是html代码:
<div class="main-editor" ng-controller="LineNumberController">
<div class="line-numbers">
<div ng-repeat="line in lines" id="line{{ $index + 1 }}">{{ $index + 1 }}</div>
</div>
<div class="editor-container">
<textarea name="editor" id="editor" cols="30" rows="10" ng-keyup="updateLineNumber()"></textarea>
</div>
</div>
答案 0 :(得分:1)
这是一种在ng-model
重要的部分是使用ng-trim="false"
,否则ng-model
将在最后一个字符
var lineCount = 1;
$scope.$watch('model.editor', function(nV, oV) {
if (!nV) {
$scope.lines = [1];
} else {
var lines = nV.split(/\r|\r\n|\n/);
// create new array if number of lines changed
if (lines.length !== lineCount) {
$scope.lines = lines.map(function(_, i) {
return i + 1
});
lineCount = lines.length;
}
}
});
查看
<div class="line-numbers">
<div ng-repeat="line in lines" id="line{{ $index + 1 }}">{{ line }}</div>
</div>
<div class="editor-container">
<textarea name="editor" id="editor" cols="30" rows="10" ng-model="model.editor" ng-trim="false"></textarea>
</div>
注意这在移除数据时也有效。
的 DEMO 强>