0

Requirement: Create a generic controller function in Angular JS that will cater to all the input types.

2 Answers 2

1

What you want then is to:

  • add the filled css class when the form field has a value, and
  • remove the filled css class when the form field doesn't have a value
  • do both of the above using a reusable function in an angular controller.

You can achieve this using Angular's built-in ng-class directive:

HTML:

<input 
    id="renewccCVV" 
    type="number" 
    class="form-control" 
    ng-class="isFilled(RenewCard.cvv)" 
    ng-model="RenewCard.cvv" 
    maxlength="4" />

JS:

$scope.isFilled = function(value){
    return (!!value) ? "filled" : "";
}

Example Plunk

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

1 Comment

Thank you Matthew, it really helped with all the browser.
0

Add the below code to Angular js controller. 'filled' is the css class that I want to make use of. I am passing the $event from my ng-blur event in HTML input control.

$scope.addCssClass = function (event) {
    if (event !== null && event.target !== null) {
        if (event.target.value !== "") {
            if (event.target.className.search('filled') < 0) {
                var classes = event.target.className;
                classes += ' filled';
                event.target.className = classes;
            }
        }
        else {
            event.target.classList.remove('filled');
        }
    }
};

Here is the snippet of HTML code.

<input id="renewccCVV" type="number" class="form-control"  ng-blur="addCssClass($event)" ng-model="RenewCard.cvv" maxlength="4" />

If my input control has value and css class 'filled' is not added to ng-class , then add the css class, if the input already has css class and value is not null, do not add the class. When the value from input control is removed, then remove the css class from the classList.

Comments

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.