我使用弹性指令从this answer调整textarea的大小。
但是我在textarea上使用ng-show,并且点击textarea的0
是<textarea ng-show="showOnClick" elastic ng-model="someProperty"></textarea>
<a ng-click="showOnClick = true"> Show text area </a>
。
所以我需要以某种方式使用$ watch来触发点击指令,但不知道如何。
HTML:
.directive('elastic', [
'$timeout',
function($timeout) {
return {
restrict: 'A',
link: function($scope, element) {
$scope.initialHeight = $scope.initialHeight || element[0].style.height;
var resize = function() {
element[0].style.height = $scope.initialHeight;
element[0].style.height = "" + element[0].scrollHeight + "px";
};
element.on("input change", resize);
$timeout(resize, 0);
}
};
}
]);
指令:
Calendar
这是JSFIDDLE
答案 0 :(得分:1)
根据要求,解决方案是$ $观察ngShow attr并在值为true时运行某种init函数。
user produced jsfiddle 示例代码:
.directive('elastic', [
'$timeout',
function($timeout) {
return {
restrict: 'A',
scope: {
ngShow: "="
},
link: function($scope, element, attr) {
$scope.initialHeight = $scope.initialHeight || element[0].style.height;
var resize = function() {
element[0].style.height = $scope.initialHeight;
element[0].style.height = "" + element[0].scrollHeight + "px";
};
if (attr.hasOwnProperty("ngShow")) {
function ngShow() {
if ($scope.ngShow === true) {
$timeout(resize, 0);
}
}
$scope.$watch("ngShow", ngShow);
setTimeout(ngShow, 0);
}
element.on("input change", resize);
$timeout(resize, 0);
}
};
}
]);