0

在我的 angular.js 应用程序中,我正在渲染一个绑定到用户可以输入数量的范围变量的输入字段。

我现在要做的是拦截对绑定变量的所有更改,如果输入了非整数数量或该字段留空,我想将我的范围变量设置为 1。

我设法通过手表做到了这一点,但我遇到了错误,因为我的数量变量也在我的手表功能中被修改:

$scope.$watch('quantity', function (oldValue, newValue) {
    // Some Code ...
    if (!valid) {
        $scope.quantity = 1;
    }
});

任何想法表示赞赏

4

2 回答 2

1

如果我理解正确,您可以对仅数字部分或您的问题使用指令,这是我编写和使用的指令,我不知道这是否会解决您的手表功能问题:

myApp.directive('numbersOnly', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, modelCtrl) {
            modelCtrl.$parsers.push(function(inputValue) {
                // this next if is necessary for when using ng-required on your input.
                // In such cases, when a letter is typed first, this parser will be called
                // again, and the 2nd time, the value will be undefined
                if (inputValue == undefined)
                    return ''
                var transformedInput = inputValue.replace(/[^0-9]/g, '');
                if (transformedInput != inputValue) {
                    modelCtrl.$setViewValue(transformedInput);
                    modelCtrl.$render();
                }

                return transformedInput;
            });
        }
    };
});

我还使用ngBlur(AngularJS 1.2 之前的)指令来限制手表执行的回调,不知道这对您的实例是否有帮助。

于 2013-08-26T16:41:39.087 回答
1

你可以用$timeoutto force来做scope.apply。简单地说,你可以这样做

$scope.check = function () {
    // Some Code ...
    if (!valid) {
        $timeout(function () {
            $scope.quantity = 1;
        });
    }
};

DEMO

于 2013-08-26T17:02:34.797 回答