Muhammad Adeel Zahid
Muhammad Adeel Zahid

Reputation: 17794

Angularjs directive to add a class to form inputs on form's submit event

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?

Upvotes: 3

Views: 784

Answers (1)

dfsq
dfsq

Reputation: 193301

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

Upvotes: 2

Related Questions