javascript - angular.js 防止空数

标签 javascript angularjs angularjs-directive

我试图强制具有必需属性的输入数字始终具有某个值,而空值则为零。
<input ng-model='someModel' required>
我创建了下一个指令:

App.directive('input', function () {
    return {
        scope: {},
        link: function ($scope, $element, $attrs) {
            if ($attrs.type == 'number') {
                if ($element[0].required) {
                    $element.on('blur', function(){
                        if(this.value===''){
                            this.value=0;
                        }
                    });
                }
            }
        }
    };
});   

我知道使用 this.value 是错误的,因为它改变了值而不是范围。但我不知道如何更改范围本身。 $scope.value根本不工作。
我希望该指令尽可能通用,因此我不想在范围内指定模型名称。

最佳答案

这是另一种方法。

App.directive('input', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs) {
            if (attrs.type === 'number' && attrs.required) {

                function update() {
                  if (!scope[attrs.ngModel]) {
                    scope.$apply(function() {
                      scope[attrs.ngModel] = 0;
                    });
                  }
                }

                element.on('blur', update)

                // remove listener when scope is destroyed
                scope.$on('$destroy', function() {
                  element.off('blur', update)
                })

            }
        }
    };
});

http://plnkr.co/edit/4yDTNUfdpu2ql1EmTZ3B?p=preview

关于javascript - angular.js 防止空数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31062910/

相关文章:

javascript - 如何检查谷歌日历API请求是否已完成?

javascript - 如何从 Sequelize 模型自动生成迁移

angularjs - ng-repeat 只显示最后一个值

angularjs - 范围:true in angularjs directive是什么意思

javascript - IE9图片过多时触发img元素onerror事件

javascript - 每个列表列的最后一项的样式不同

javascript - 延迟的 Angular $timeout

javascript - 使用 $scope.apply() 后点击展开不工作

django - 图片上传指令(angularJs 和 django rest 框架)

javascript - 如何在 Controller 中加载指令?