在元素中选择文本

Ted*_*Ted 5 javascript jquery angularjs angular-directive

我有一个input元素,并且通过使用ng-model在其中包含文本,然后我尝试通过创建自定义侦探来选择所有文本:

.directive('selectText', function() {
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
            elem.bind('focus', function() {
                $(elem).select();
            });
            scope.$watch("edit",function(newValue,oldValue) {
                $(elem).select();
            });
        }
    };
})
Run Code Online (Sandbox Code Playgroud)

它工作得很好,但我不想让用户foucusout从控件中focusin再次选择它的文本.它应该只选择一次文本(而不是第二次焦点).另外,当选择所有文本时,如何从元素中删除焦点?

Max*_*Max 0

您可以创建在选择元素时保存布尔值的变量,并仅在尚未选择元素时选择该元素。像这样:

.directive('selectText', function() {
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
            var selected = false;
            elem.bind('focus', function() {
                if (!selected) {
                    $(elem).select();
                    selected = true;
                }
            });
            scope.$watch("edit",function(newValue,oldValue) {
                $(elem).select();
            });
        }
    };
})
Run Code Online (Sandbox Code Playgroud)