1

I am trying to replace any spaces in my input on change. I am using ng-change directive to accomplish that. I would normally write my code like this because I want the removeInvalidCharacters function to be reusable hence the model being passed as parameter.

<input model="vm.model.code" ng-change="vm.removeInvalidCharacters(vm.model.code)" />

and JS

vm.removeInvalidCharacters = function(text) {
  text = text.replace(/ /g, '');
};

I have read on the airbnb javascript style guide that this is a bad practice and we should return the value. To be exact we shouldn't "mutate a parameter" (Never reassign parameters). What is the right way to do it and still keep the reusable function?

1
  • Not entirely clear on what exactly is being asked. You shouldn't come in behind a user during input and change their value "out from under their feet". If you need to clean up input, do it on form submission or the-like. If you need to validate, use regex to just catch patterns your cleanup method can't handle. Commented Nov 30, 2020 at 22:36

1 Answer 1

1

ng-change is a directive that gets triggered every time there is a change in the model through the template.

In your code you are declaring a variable 'text' as a parameter with the value of 'vm.model.code'. But your changes are being made to the local variable 'text' and not in the variable used in the template

Use this instead:

vm.removeInvalidCharacters = function(text) {
  vm.model.code = text.replace(/ /g, '');
};

Edit:

If what you are looking for is passing the variable as reference instead of parameter check this answer: Pass $scope variable to function by reference

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

2 Comments

That's what I wanted to do in the first place but what if I wanted to make vm.removeInvalidCharacters generic? e.g. change any of the model's properties vm.model.email etc. What I have been suggesting by the use of local 'text' is the way of mutating the parameter but what if I wanted to apply some common practices to this scenario?
What you are looking for is to pass a parameter as a reference instead of parameter which is not possible in Javascript without a workaround, also, Angular.js needs to be aware of the changes so it can do a digest cycle and apply the changes so I would recommend using the model instead because of that. If that doesn't stop you I updated my answer with an existing answer with a working workaround @LazioTibijczyk

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.