3

我有一个实例,我正在替换ngModelthrough的值ngChange。每次更改后,光标都会跳到input字段的末尾(假设因为我将结果分配给同一个$scope变量。)
我想知道如何防止这种行为?

  $scope.compute1 = 0;
  $scope.compute2 = 10;

  $scope.math = function() {
    $scope.compute1 = parseInt($scope.compute1);
    $scope.compute2 = parseInt($scope.compute2);

    $scope.compute1 = parseInt($scope.compute1);
  };

小提琴

问题示例:如果用户输入 1000。没关系。但是如果他们想返回并通过添加 5 和 6 将数字更改为 156000,则 6 实际上会附加到末尾:15006。

4

5 回答 5

2

两个建议:

1为什么不只使用数字输入。

<div ng-app='myApp'>
    <div ng-controller="myCtrl">
    <input id="compute1" ng-model="compute.c1" ng-change="math()" type="number"/>
    <input id="compute2" ng-model="compute.c2" ng-change="math()" type="number"/>
  </div>
</div>

2双向数据绑定应始终与“点”表示法一起使用:

$scope.compute = {c1: 0, c2: 10};

$scope.math = function() {
  $scope.compute.c1 = parseInt($scope.compute.c1);
  $scope.compute.c2 = parseInt($scope.compute.c2);
};

并相应地更新您的 html 以具有 ng-model="compute.c1" 等。

于 2013-11-25T21:15:37.810 回答
2

光标移动到末尾是因为我们使用parseInt.

我建议您先存储插入符号的位置,然后在完成操作后将其放回原处。

这个例子可能会帮助你:Link

于 2013-11-25T21:22:46.423 回答
1

根据math()具体操作,您可以使计算发生在模糊而不是更改上。这样,只有当用户选择(或单击)输入时才会发生转换。

有关此示例,请参见Angularjs: input[text] ngChange 在值更改时触发

于 2013-11-25T21:42:17.063 回答
0

我刚刚写了这个指令,它基本上允许你格式化文本并保持光标位置它不是完美无缺的,但效果很好。只需确保在格式函数中返回值,而不是实际更改值并像使用常规 ng-change 一样使用它:

.directive('ngChangeFormat', function() {
        return {
            restrict: 'A',
            require: '?ngModel',
            link: function(scope, element, attr, controller) {
                controller.$viewChangeListeners.push(function() {
                    var el = element[0];
                    var start = el.selectionStart;
                    var end = el.selectionEnd;
                    var originalValue = controller.$viewValue;
                    var formattedValue = scope.$eval(attr.ngChangeFormat);
                    controller.$setViewValue(formattedValue);
                    controller.$render();
                    if(start === originalValue.length)
                        el.setSelectionRange(formattedValue.length, formattedValue.length);
                    else
                        el.setSelectionRange(start, end);
                });
            }
        };
    })
于 2016-04-05T08:46:26.287 回答
0

非常快速和简单的修复来延迟 ng-model-options。我遇到了同样的问题,这对我有用:根据您的输入->

ng-model-options="{debounce: 750}"
于 2018-07-31T11:25:50.143 回答