绑定到文本突出显示

Bind to text highlighting

本文关键字:显示 文本 绑定      更新时间:2023-09-26

我正在尝试将控制器操作绑定到文本区域、文本输入或内容可编辑中突出显示的文本。假设我有:

<input type="text" ng-model="name" placeholder="Enter Name">

使用 Angular 1.2.0,如何监视文本框内突出显示的文本并在页面上为用户显示某些内容?

这是使用 $timeout 的指令的粗略实现。 它可以通过监控mouseupkeyup(或选择事件,如果存在)来改进。

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 = '';
});
您可以

创建一个指令来利用输入元素的selectionStartselectionEnd属性来实现您想要完成的任务,如下所示:

.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>

http://plnkr.co/edit/4LLfWk110p8ruVjAWRNv

以下是从input字段中获取所选文本的方法:

http://jsfiddle.net/vREW8/

var input = document.getElementsByTagName('input')[0];
var selectedText = input.value.substring(input.selectionStart, input.selectionEnd);

你可以用任何你想要的方式.js与Anuglar一起使用。