我是Angular和Web开发的新手,当在Angular中单击按钮时,我有一个需要选择(突出显示)的文本输入区域。
我需要像angular.element(document.getElelmentById(txt1))这样的东西并选择吗?
与此主题相似: Selecting all text in HTML text input when clicked,问题是,在Angular中有没有正确/更好的方法呢?
我已经搜索了一个答案,我最接近的是这个帖子:How to set focus on input field?但是无法成功转换select()的建议。
这是我在简单js中的jsfiddle:http://jsfiddle.net/x62ye14y/,对于angular的翻译将非常感激。
<!DOCTYPE html>
<html>
<body>
Select your favorite fruit:
<input type="text" id="id123" placeholder="ENTER VALUE">
<p>Click the button to select text in the textbox</p>
<button onclick="myFunction()">Select Txt</button>
<script>
function myFunction() {
document.getElementById("id123").select();
}
</script>
</body>
</html>
这是我到目前为止的代码:
<!DOCTYPE html>
<html ng-app="demo">
<head lang="en">
<meta charset="utf-8">
<title>Custom Plunker</title>
</head>
<body>
<div ng-controller="DemoCtrl">
<input type="text" ng-model="content" id="txt1"/>
<button ng-click="selectOnClick()">Select Txt</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js">
</script>
<script type="text/javascript">
var mod1 = angular.module('demo', []);
mod1.controller('DemoCtrl', function ($scope) {
$scope.content = 'some text';
});
mod1.directive('selectOnClick', function () {
// Linker function
var element1 = angular.element("txt1");
element1.select();
});
</script>
</body>
</html>
答案 0 :(得分:2)
你可以试试这个:
http://plnkr.co/edit/PzcINVKw6KNBFxlZUgAS?p=preview
<!DOCTYPE html>
<html ng-app="demo">
<head lang="en">
<meta charset="utf-8">
<title>Custom Plunker</title>
</head>
<body>
<div ng-controller="DemoCtrl">
<input type="text" ng-model="content" select-on-click />
<p>Content: {{content}}</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="app.js"></script>
</body>
</html>
应用程式:
(function (angular) {
var module = angular.module('demo', []);
module.controller('DemoCtrl', function ($scope) {
$scope.content = 'foobar';
});
module.directive('selectOnClick', function () {
// Linker function
return function (scope, element, attrs) {
element.bind('click', function () {
this.select();
});
};
});
}(angular));
您只需将选择点击移至按钮
即可答案 1 :(得分:0)
简单的方法是使用click
事件。
例如
<input type = "text" (click) = "$event.target.select()">