【发布时间】:2014-11-08 02:11:12
【问题描述】:
我正在编写一个简单的 Angular 指令,用于在 textarea 旁边显示行号。但是,由于某种原因,$watch 表达式不会触发更新。代码如下:
mod.directive('newTextArea', function() {
return {
restrict: 'E',
scope: {
query: '='
},
template:
'<div>' +
' <div ng-style="{height: height}" style="width: 20px; float: left; color: gray; font-family: Courier New; font-size: 14px; overflow: hidden; height: 85px; position: relative; top: 5px;">' +
' <div style="position: absolute">' +
' <span ng-repeat="line in lines">{{line}}<br></span>' +
' </div>' +
' </div>' +
' <textarea id="query-area" style="overflow-x: scroll; font-family: Courier New; font-size: 14px;">' +
' </textarea> {{ lines }}' +
'</div>',
controller: function($scope, $attrs, $element) {
var textarea = document.getElementById('query-area');
function updateLayout() {
var st = textarea.scrollTop;
var h = textarea.scrollHeight;
$scope.height = h;
console.log(st, h);
if (st !== undefined && h !== undefined) {
var start = Math.round(st / 14);
var stop = Math.round((st + h) / 14);
$scope.lines = _.range(start+1, stop+1);
}
}
$scope.$watch(
function() {
return [textarea.scrollHeight, textarea.scrollTop];
}, updateLayout, true
);
}
};
文本区域滚动或大小发生变化时,行号应立即更新。知道为什么这不起作用吗?
【问题讨论】:
标签: javascript angularjs dom textarea