简体   繁体   中英

(AngularJS Directive) Change model value on input blur

I have a ng-model input element where I would like to enter just integer, positive numbers, but in case of empty input set model value to "1".

I have created a directive, but after input blur it does not change model value to "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;
        });
    }
  };
});

Here is live JSFiddle example: http://jsfiddle.net/buh86w8n/2/

Is there anyone who could help me?

elem.on('blur', function(){ // code..}) is out side angular scope.

To change scope value inside elem.on blur event you have to call $apply() .

Here is working plunkr

elem.on blur event :

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

Or you can just $watch for that input, if its empty set it on 1.

So it starts with 2, if u delete it it will be set to 1, else set it on any number.

Here is your code edited:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM