【问题标题】:angularJs - update range and number input simultaniously failsangularJs - 更新范围和数字输入同时失败
【发布时间】:2015-03-30 10:11:22
【问题描述】:

我想使用 AngularJs 同时更改范围和输入框,但出现此错误:“http://errors.angularjs.org/1.3.11/ngModel/numfmt?p0=0.6

我认为原因是使用字符串而不是数值更新模型的范围,但这并没有让我更接近解决方案。

<html ng-app="app">
    <div ng-controller="controller">
        <input type="number" min="0" max="1" step="0.1" ng-model="value" />
        <input type="range" min="0" max="1" step="0.1" ng-model="value"/>
    </div>
</html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
<script>
    var app = angular.module('app', []);
    app.controller('controller', function($scope) {
        $scope.value = 0.5;
});
</script>

如何在不报错的情况下更改输入框应用的范围?

注意:显而易见的解决方案是将输入框的类型更改为“文本”,但我不想在那里允许非数字值。

【问题讨论】:

    标签: angularjs validation input


    【解决方案1】:

    你可以使用 parseFloat:

    <!doctype html>
    <html>
        <head>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.js"></script>
        </head>
        <body ng-app="boltlandApp">
            <div ng-controller="controller">
                <input type="number" min="0" max="1" step="0.1" ng-model="value" />
                <input type="range" min="0" max="1" step="0.1" ng-model="range"/>
            </div>
        </body>
        <script>
        var app = angular.module('boltlandApp', []);
        app.controller('controller', function($scope) {
            $scope.value = 0.5;
            $scope.range = 0.5;
            $scope.$watch('range', function (newVal, oldVal) {
                $scope.value = parseFloat(newVal);
            });
            $scope.$watch('value', function (newVal, oldVal) {
                $scope.range = newVal;
            });
        });
        </script>
    </html>

    【讨论】:

    • 感谢您的回答,但似乎也有更简单的解决方法。
    【解决方案2】:

    似乎是一个错误: https://github.com/angular/angular.js/issues/5892

    解决方法是:

    $scope.$watch('value', function() {
        $scope.value = parseFloat($scope.value);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-02
      • 1970-01-01
      • 2021-01-19
      • 2013-03-17
      • 1970-01-01
      相关资源
      最近更新 更多