绑定到文本高亮 [英] Bind to text highlighting
本文介绍了绑定到文本高亮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图绑定一个控制器动作的文本是在文本区域,输入文字或内容编辑的高亮显示。假设我有:
I am trying to bind a controller action to text that is highlighted in a text area, text input, or content-editable. Suppose that I have:
<input type="text" ng-model="name" placeholder="Enter Name">
通过角1.2.0,我怎么能看的是高亮的文本框,并显示在页面上,为用户的东西的文字?
With Angular 1.2.0, how can I watch for text that is highlighted inside the text box and display something on the page for the user?
推荐答案
下面是pretty粗糙的实现,它使用 $超时
A指令。这可能可能是由监控,提高鼠标松开
和 KEYUP
(或者如果存在的话选择事件)。
Here is a pretty rough implementation of a directive that uses $timeout
. It could probably be improved by monitoring mouseup
and keyup
(or selection events if they exist).
http://jsfiddle.net/4XDR8/1/
HTML
<div ng-app="app" ng-controller="TestCtrl">
<input type="text" placeholder="Enter Name" ng-get-selection="name">
{{name}}
<br/>
<br/>here select all this text down here
</div>
JavaScript的:
JavaScript:
var app = angular.module('app', []);
app.directive('ngGetSelection', function ($timeout) {
var text = '';
function getSelectedText() {
var text = "";
if (typeof window.getSelection != "undefined") {
text = window.getSelection().toString();
} else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
text = document.selection.createRange().text;
}
return text;
}
return {
restrict: 'A',
scope: {
ngGetSelection: '='
},
link: function (scope, element) {
$timeout(function getSelection() {
var newText = getSelectedText();
if (text != newText) {
text = newText;
element.val(newText);
scope.ngGetSelection = newText;
}
$timeout(getSelection, 50);
}, 50);
}
};
});
app.controller('TestCtrl', function ($scope) {
$scope.name = '';
});
这篇关于绑定到文本高亮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文