[英]How can I run a controller function only after textarea fully loaded?
I have a textarea like below:我有一个如下的文本区域:
<textarea rows="3" maxlength="144" ng-maxlength="144" type="text"
name="testPost" id="testPost_{{item.id}}"
ng-init="focusText('testPost', item.id)"
ng-model="item.testPost">
</textarea>
with a function like below:使用 function 如下所示:
$scope.focusText = function (columnSelected, id){
if(columnSelected == "testPost"){
var textId = "testPost_" + id;
document.getElementById(textId).focus();
document.getElementById(textId).setSelectionRange(0,0);
}
}
The problem is, document.getElementById(textId)
is null
as function is ran before the textarea is loaded.问题是, document.getElementById(textId)
是null
因为 function 在加载 textarea 之前运行。 How can I run the function only after textarea is loaded?如何仅在加载 textarea 后运行 function?
The problem is,
document.getElementById(textId)
isnull
问题是,document.getElementById(textId)
是null
Create a custom directive:创建自定义指令:
app.directive("myInit", function() {
return {
link: postLink
};
function postLink(scope, element, attrs)
scope.$eval(attrs.myInit, {$element: element})
}
})
Then pass the $element
local to the function:然后将$element
local 传递给 function:
<textarea rows="3" maxlength="144" ng-maxlength="144" type="text"
name="testPost" id="testPost_{{item.id}}"
my-init="focusText('testPost', item.id, $element)"
ng-model="item.testPost">
</textarea>
Use the $element
parameter in the focusText
function:在focusText
function中使用$element
参数:
$scope.focusText = function (columnSelected, id, $element){
if(columnSelected == "testPost"){
$element[0].focus();
$element[0].setSelectionRange(0,0);
}
}
This avoids using document.getElementById
and the error.这避免了使用document.getElementById
和错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.