Skip to content Skip to sidebar Skip to footer

Ngmodel.$parsers Ingore Whitespace At The End Of Ng-model Value

I have directive like this: .directive('noWhitespace', ['$parse', function($parse) { return { restrict: 'A', require: 'ngModel', link: function (scope, elem

Solution 1:

Try this in your template:

<formname="something"novalidate><inputng-model="myValue"no-whitespaceng-trim="false"/><divng-show="something.myValue.$error.whitespace">
    Error
  </div></form>

That should solve the issue of ng-model not updating when you enter empty space.

EDIT: Derp, the attribute goes in the input element not in the div ...

Solution 2:

This is the expected behavior of model parsers in angular, the idea being that if the entered text is incorrect (has whitespace in the end), the ngModel should return undefined. When you think about it, why would you save a value to ngModel anyway if it's not correct according to your validations?

This is the relevant bit:

if (viewValue.match(/\s/)) {
  ngModel.$setValidity('whitespace', false);
  returnundefined;
}

You are setting validity to false and returning undefined.

You can keep the model updated even if its value isn't validated by just returning viewValue always:

if (viewValue.match(/\s/)) 
  ngModel.$setValidity('whitespace', false);
else 
  ngModel.$setValidity('whitespace', true);

// Return viewvalue regardless of whether it validates or notreturn viewValue;

Post a Comment for "Ngmodel.$parsers Ingore Whitespace At The End Of Ng-model Value"