テキスト領域、テキスト入力、またはコンテンツ編集可能で強調表示されているテキストにコントローラー アクションをバインドしようとしています。私が持っているとします:
<input type="text" ng-model="name" placeholder="Enter Name">
Angular 1.2.0 では、テキスト ボックス内で強調表示されているテキストを監視し、ユーザーのためにページに何かを表示するにはどうすればよいですか?
テキスト領域、テキスト入力、またはコンテンツ編集可能で強調表示されているテキストにコントローラー アクションをバインドしようとしています。私が持っているとします:
<input type="text" ng-model="name" placeholder="Enter Name">
Angular 1.2.0 では、テキスト ボックス内で強調表示されているテキストを監視し、ユーザーのためにページに何かを表示するにはどうすればよいですか?
を使用するディレクティブのかなり大まかな実装を次に示します$timeout
。mouseup
おそらく監視とkeyup
(または存在する場合は選択イベント)によって改善される可能性があります。
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:
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 = '';
});
次のように、達成したいことを達成するために使用するディレクティブと入力要素のプロパティを作成できますselectionStart
。selectionEnd
JS:
directive('watchSelection', function() {
return function(scope, elem) {
elem.on('mouseup', function() {
var start = elem[0].selectionStart;
var end = elem[0].selectionEnd;
scope.selected = elem[0].value.substring(start, end);
scope.$apply();
});
};
});
HTML:
<input type="text" ng-model="name" placeholder="Enter Name" watch-selection>
input
フィールドから選択したテキストを取得する方法は次のとおりです。
var input = document.getElementsByTagName('input')[0];
var selectedText = input.value.substring(input.selectionStart, input.selectionEnd);
Anuglar.js で任意の方法で使用できます。