Lessy Lessy - 5 months ago 14
AngularJS Question

Value of model is gone when custom directive is applied to a input field

I have an input field as such, where i apply a custom directive for validation.

<input type="text" data-ng-model="ev.name" ischanged="{{d.EventName}}"/>


The directive is as such :

app.directive('ischanged', function () {
'use strict';
return {
require: 'ngModel',
link: function (scope, elem, attr, ctrl) {
ctrl.$parsers.unshift(function (input) {

if(attr.ischanged == input) {
ctrl.$setValidity('ischanged', false);
}
else if(attr.ischanged != input)
{
ctrl.$setValidity('ischanged', true);
}
});

}

};
});


The directive compares the value with another value, and sets the validity of the field accordingly. But, when i apply this directive.
{{ev.name}}
will show nothing as I enter value into it.

{{ev.name}}
fine when I remove the directive entirely.

I realized this problem when I tried to update through http.put, it says that the one of the data is empty.

Answer

You were missing a return statement to update the model in your directive. I added one just to update the model if the value is valid. You can decide how you want to handle the invalid case.

app.directive('ischanged', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elem, attr, ctrl) {
      ctrl.$parsers.unshift(function(input) {

        if (attr.ischanged == input) {
          ctrl.$setValidity('ischanged', false);
          return input ? input : undefined;
        } else if (attr.ischanged != input) {
          ctrl.$setValidity('ischanged', true);
        }
      });
    }
  };
});

Here's a working plunker that also includes some HTML changes as well so that you can see the validation working and the model updating.

Comments