3

I am using ng-class to add submitted class to my inputs when form is submitted like

<form name="myform" novalidate>
<input name= "input1" ng-class="{'submitted':myform.$submitted}" ng-model=data.input1/>
.....
....
</form>

Although it gets the job done but it is too verbose and I have many inputs where I need this. I want to create a directive to make my html look like

<form name="myform" novalidate>
<input name= "input1" set-submitted ng-model=data.input1/>
.....
....
</form>

How can I create a directive for this purpose?

2
  • Why not add class to form itself in only one place instead of all elements? Commented Dec 28, 2014 at 11:00
  • Frankly, I just wanted to know how I can create a directive for this particular purpose. yes you are right about adding class to the form and ng-submitted class is automatically added to the form when it is submitted Commented Dec 28, 2014 at 11:09

1 Answer 1

2

It's better to simply use ng-submitted class that is automatically set on form by Angular on form submit.

However for academic purposes here is a simple directive to set class on elements itself:

app.directive('setSubmitted', function() {
    return {
        require: '^form',
        link: function(scope, element, attrs, ngFormController) {
            scope.$watch(function() { 
                return ngFormController.$submitted;
            }, function(newVal, oldVal) {
                if (newVal !== oldVal) {
                    element.toggleClass('submitted', newVal);
                }
            })
        }
    };
});
Sign up to request clarification or add additional context in comments.

3 Comments

can u please explain second argument to toggleClass?
does this function comes from jquery or its core angular?
This is a method of angular.element, implementation of jQuery's toggleClass method. The second boolean argument determines if the class should be added (true) or removed (false). You could also use if block with addClass and removeClass.

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.