使用Angularjs

时间:2017-08-07 17:01:49

标签: javascript angularjs

如何使用text cursor阻止$scope.$watch跳转到textarea字段的结尾?

//textarea $watch
$scope.$watch('string', function(s){
    var string = s.split('\n');
    if(string.length > 0) {
        var newElements = [];
        for (var i = 0; i < string.length; i++) {
            var str = string[i];
            var obj = {};
            var firstMatch = str.split('|')[0];
            var secondMatch = str.substring(firstMatch.length + 1); //return '' if '|' was not found

            obj.text = firstMatch;
            obj.value = secondMatch;

            newElements.push(obj);
        }
        $scope.elements = newElements;
    }
});

//array of objects $watch
$scope.$watch('elements', function(e){
    var string = '';
    for(var i = 0; i < e.length; i++){
        var str = e[i];
        var value = str.value;
        var pipe = '|';
        var text = str.text;
        if( value == ''){
            pipe = '';
        }
        string += (text + pipe + value) + (i == e.length - 1 ? '' : "\n");
    }
    $scope.string = string;
}, true);

清除值后,text cursortextarea内)始终跳到最后。例如:尝试清空value1处的第一个值(textarea),光标移动到行尾(value1为空后,文本光标移至行尾,但我希望光标保持在它被清空的位置。

text1|value1 <-- after the value1 is empty, the text cursor goes to the end of line, but I want the cursor to stay here or to the position that It was emptied
text2|value2
text3|value3
text4|value4 <-- cursor goes here after emptied
  • 我想阻止光标移动到最后。

试试这里: https://jsfiddle.net/yegrteaf/3/

0 个答案:

没有答案