0

テキスト領域、テキスト入力、またはコンテンツ編集可能で強調表示されているテキストにコントローラー アクションをバインドしようとしています。私が持っているとします:

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

Angular 1.2.0 では、テキスト ボックス内で強調表示されているテキストを監視し、ユーザーのためにページに何かを表示するにはどうすればよいですか?

4

3 に答える 3

3

を使用するディレクティブのかなり大まかな実装を次に示します$timeoutmouseupおそらく監視と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-30T17:27:34.627 に答える
1

次のように、達成したいことを達成するために使用するディレクティブと入力要素のプロパティを作成できます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

于 2013-09-30T17:48:05.427 に答える
0

inputフィールドから選択したテキストを取得する方法は次のとおりです。

http://jsfiddle.net/vREW8/

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

Anuglar.js で任意の方法で使用できます。

于 2013-09-30T17:32:00.267 に答える