我试图将控制器操作绑定到文本区域、文本输入或内容可编辑中突出显示的文本。假设我有:
<input type="text" ng-model="name" placeholder="Enter Name">使用角1.2.0,我如何观察文本框中突出显示的文本,并在页面上为用户显示一些内容?
发布于 2013-09-30 17:27:34
下面是使用$timeout的指令的一个相当粗略的实现。它可能通过监视mouseup和keyup (或者如果存在选择事件)而得到改进。
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:
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 = '';
});发布于 2013-09-30 17:48:05
您可以创建一个指令来利用输入元素的selectionStart和selectionEnd属性来实现您想要完成的任务,如下所示:
联署材料:
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>http://plnkr.co/edit/4LLfWk110p8ruVjAWRNv
发布于 2013-09-30 17:32:00
下面是如何从input字段获取所选文本:
http://jsfiddle.net/vREW8/
var input = document.getElementsByTagName('input')[0];
var selectedText = input.value.substring(input.selectionStart, input.selectionEnd);您可以随心所欲地在Anuglar.js中使用它。
https://stackoverflow.com/questions/19099851
复制相似问题