Search code examples
javascriptangularjsinputmodelonblur

(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?


Solution

  • 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();
        }
    });