0

I want to change the user input and model using a cutom directive like:

app.directive('changeInput', function ($parse) {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            //insert logic here
            });
        }
    };
});

So any time the user will insert char in:

<input 
   name="inputText" 
   type="text"
   change-input
   data-ng-model="data.name"
>

The input will change from 'a' to 'b' for example. I just need the right logic for the change, I hane tried using $event and preventDefault() but it created more problams.

Thanks.

3
  • Its not clear what you asking. What should happen if the input change from "a" to "b"? Commented Feb 20, 2017 at 8:39
  • How to change the user input from a to b using directive. Commented Feb 20, 2017 at 8:40
  • The user insert a but b will appear. Commented Feb 20, 2017 at 8:43

1 Answer 1

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

      }
    }
  };
});
Sign up to request clarification or add additional context in comments.

4 Comments

Great, but if I want to change string input.
@ItsikMauyhas I updated my answer if you need anything more specific please provide me with more information
Hi, the view does not update in $parsers block, is there a way?
@ItsikMauyhas try it now I modified the code this means a digest cycle is already ongoing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.