我想在我的项目中使用此directive,但我希望文本区域在内容加载的时刻扩展。
角-Autogrow.js:
(function(){
'use strict';
angular.module('angular-autogrow', []).directive('autogrow', ['$window', function($window){
return {
link: function($scope, $element, $attrs){
/**
* Default settings
*/
$scope.attrs = {
rows: 1,
maxLines: 999
};
/**
* Merge defaults with user preferences
*/
for(var i in $scope.attrs){
if($attrs[i]){
$scope.attrs[i] = parseInt($attrs[i]);
}
}
/**
* Calculates the vertical padding of the element
* @returns {number}
*/
$scope.getOffset = function(){
var style = $window.getComputedStyle($element[0], null),
props = ['paddingTop', 'paddingBottom'],
offset = 0;
for(var i=0; i<props.length; i++){
offset += parseInt(style[props[i]]);
}
return offset;
};
/**
* Sets textarea height as exact height of content
* @returns {boolean}
*/
$scope.autogrowFn = function(){
var newHeight = 0, hasGrown = false;
if(($element[0].scrollHeight - $scope.offset) > $scope.maxAllowedHeight){
$element[0].style.overflowY = 'scroll';
newHeight = $scope.maxAllowedHeight;
}
else {
$element[0].style.overflowY = 'hidden';
$element[0].style.height = 'auto';
newHeight = $element[0].scrollHeight - $scope.offset;
hasGrown = true;
}
$element[0].style.height = newHeight + 'px';
return hasGrown;
};
$scope.offset = $scope.getOffset();
$scope.lineHeight = ($element[0].scrollHeight / $scope.attrs.rows) - ($scope.offset / $scope.attrs.rows);
$scope.maxAllowedHeight = ($scope.lineHeight * $scope.attrs.maxLines) - $scope.offset;
$element[0].addEventListener('input', $scope.autogrowFn);
/**
* Auto-resize when there's content on page load
*/
if($element[0].value != ''){
$scope.autogrowFn();
}
}
}
}]);
})();
我改变了:
// $element[0].addEventListener('input', $scope.autogrowFn);
$element[0].addEventListener('load', $scope.autogrowFn);//<-- I add this line
但它不起作用。如何更改它以便在加载内容时文本区域自动展开?
答案 0 :(得分:1)
您必须先使用该指令,然后在app.js中加入&#34; angular-autogrow&#34; 指令,然后检查文本区域是否会根据您输入的内容自动增长< / p>
<强> HTML 强>
<textarea autogrow></textarea>
<强> JS 强>
var app = angular.module('plunker', ["angular-autogrow"]);
app.controller('MainCtrl', function($scope) {
});
答案 1 :(得分:0)
我的HTML是:
<textarea autogrow ng-model="vm.myinput" ></textarea>
我换了:
$element[0].addEventListener('input', $scope.autogrowFn);
with:
$scope.$watch($attrs.ngModel, $scope.autogrowFn);
所以每次更改模型时,都会调用自动增长功能。这也适用于你的情况。
答案 2 :(得分:0)
由于现代浏览器支持event.target,因此还有一个最小的非angularjs替代方案,您以后无需将其升级到Angular。另外,似乎可以将“ this”(HTMLElement)作为参数访问。如果使用onscroll,则开始滚动时,textarea会增大。替代方法是onfocus或onkeyup事件。请注意,文本区域无法缩小。
如果模型以编程方式更改,则可能需要在$ watch中手动触发滚动事件:htmlElement.dispatchEvent(new Event(“ scroll”));
https://jsfiddle.net/hnxd91rq/
<textarea onscroll="autogrowTextHeight(event, this)"></textarea>
<script>
function autogrowTextHeight(event, htmlElement) {
// https://developer.mozilla.org/en-US/docs/Web/API/Event
// var htmlElement = event.target; ... OR use this ...
htmlElement.style.height = htmlElement.scrollHeight+"px";
}
</script>