(AngularJS指令)改变输入模糊的模型值

(AngularJS Directive) Change model value on input blur

本文关键字:模糊 模型 输入 改变 AngularJS 指令      更新时间:2023-09-26

我有一个ng-model输入元素,我想输入整数,正数,但在空输入的情况下,将模型值设置为"1"。

我已经创建了一个指令,但在输入模糊后,它不会改变模型值为"1":

angular.module('myapp', [])
.controller('MainCtrl', function ($scope) {
  $scope.item = { qty: 2 };
})
.directive('cartQty', function () {
  return {
    require: 'ngModel',
    link: function (scope, elem) {
        scope.$watch('item.qty', function (newValue, oldValue) {
            var arr = String(newValue).split('');
            if (arr.length == 0) return;
            if (newValue == 0) scope.item.qty = 1;
            if (isNaN(newValue)) scope.item.qty = oldValue;
        });
        elem.on('blur', function () {
            var value = String(elem[0].value);
            if (value.length == 0) scope.item.qty = 1;
        });
    }
  };
});

下面是JSFiddle的实例:http://jsfiddle.net/buh86w8n/2/

有人能帮我吗?

elem.on('blur', function(){ // code..})在外角范围

要更改elem.on blur事件中的作用域值,必须调用$apply()

这里是工作活塞

elem。on blur event:

elem.on('blur', function () {
    var value = String(elem[0].value);
    if (value.length == 0){
        scope.item.qty = 1;
        scope.$apply();
    }
});

或者您可以为该输入设置$watch,如果它为空,则将其设置为1。

所以它从2开始,如果你删除它,它将被设置为1,否则设置为任何数字

这是你的代码编辑:

http://jsfiddle.net/buh86w8n/4/