سؤال

I'm having a peculiar case on my hands. I'm using the number-polyfill for input[type="number"] in my Angular app. Now, the problem with that is that it's doesn't take into accound Angularjs's way of handling things.

Like, if I increment/decrement the input value programatically, the ngModel associated with the input does not get the updated value.

I've resolved that by writing a custom directive, and passing the model into the pollyfill

angular.module('appModule').
  directive('type', ['$parse', '$timeout', function($parse, $timeout) {
    restrict: 'A',
    require: '?ngModel',
    link: function($scope, iElement, iAttrs, ngModel) {
      ...
      if iAttrs.type is 'number'
        iElement.inputNumber(ngModel)  // <-- THIS LINE
      ...
    }
  }

In the polyfill code, I've modified this:

increment = function(elem) {
  ...
  if (model != null) {
    model.$setViewValue(newVal);
  }
  ...
}

which works perfectly. Now, the problem is that even after updating the model's value, the associated form does not become dirty. In my code, it's not possible to pass the form as an argument into this polyfill.

I tried using model.$dirty = true, but that's not working.

Any other way?

هل كانت مفيدة؟

المحلول

I figured out the error. Although the $setViewValue should have set my form to dirty, the thing which was stopping it was the fact that the code where I was doing this was out-of-$scope ;)

And, for that the $scope.$apply() comes in handy. So, now along with the model, I'm also passing in the $scope to the polyfill.

angular.module('appModule').
  directive('type', ['$parse', '$timeout', function($parse, $timeout) {
    restrict: 'A',
    require: '?ngModel',
    link: function($scope, iElement, iAttrs, ngModel) {
      ...
      if iAttrs.type is 'number'
        iElement.inputNumber(ngModel, $scope)  // <-- THIS LINE
      ...
    }
  }

increment = function(elem) {
  ...
  if (model != null) {
    $scope.$apply(function() {
      model.$setViewValue(newVal);
    }
  }
  ...
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top