Skip to content Skip to sidebar Skip to footer

Angular Directive To Change Input Values On Insert

I want to change the user input and model using a cutom directive like: app.directive('changeInput', function ($parse) { return { require: 'ngModel', link: func

Solution 1:

You could use build in parsers and formatters of ngModel When a model change is detected the formatter and parser will fire. the formatter for data from a change in the model to the view and parser for a change from the view to the model.

app.directive('changeInput', function() {
  return { restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      if(ngModel) { // Don't do anything unless we have a model

        ngModel.$parsers.push(function (value) {
        //value is a
        // 'value' should be your model property
        ngModel.$setValidity('value', true);    
        // sets viewValue

         ngModel.$setViewValue(value); 

        // renders the input with the new viewValue
        ngModel.$render()
        return "b" // you are changing it to b. so now in your controller the value is b and you can trigger your save function
        });

        ngModel.$formatters.push(function (value) {
         //value is b
         return "a" // you are changing it to a. So now in your view it will be changed to a
        });

      }
    }
  };
});

Post a Comment for "Angular Directive To Change Input Values On Insert"