0

Well basically I'm using this:

<form ng-model="form" ng-submit="save()" name="form" class="form">

And it creates a new form controller, right? I'd like to add a method "addErrors" for all my form controllers in my application, now I have to do it manually, is there a way to add it through config or run method when I'm bootstraping my app?

Regards.

1 Answer 1

2

Little known fact:
There can be multiple directives with the same name. Each one does not overwrite the previous, but rather gets applied along-side all the others.

The simplest way to achieve what you want is to define a custom directive for form elements (you will in fact need two: one for form and one for ngForm) that gets access to the FormController instance and augments it with custom behaviour.

E.g.:

app.directive('form', function () {
    return {
        restrict: 'E',
        require: 'form',   // to get access to the FormController instance
        link: function postLink(scope, elem, attrs, formCtrl) {
            formCtrl.submit = function () {
                alert(formCtrl.$valid ? '*Submit*' : '*Error*');
            };
        }
    };
});

See, also, this short demo.

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

6 Comments

it seems to work perfect! And I still get the properties of the original FormController. Thank you!
Always glad to help ! Feel free to also upvote the answer if you really liked it :)
The same does not seem to be working for ngForm - any idea why?
I created a plunk to demonstrate... plnkr.co/edit/yxVGuZr7WvKgXFcTETpP?p=preview
For some reason, I'm able to create other methods, but not "submit".
|

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.