0

I am seeking to find a clean solution to the following antipattern with my AngularJs app:

I have two forms (located in two different templates/partials as of now) which are completely identical but for the ng-submit attributes which point to different Angular controller methods.

First form:

<form ng-submit="saveTraining()" method="post" class="form-horizontal">

        <div ng-hide="trainingInfo.statusOK" class="alert alert-danger form-group">
            <ul>
                <li ng-repeat="error in trainingInfo.errors">{{error.message}}</li>
            </ul>
        </div>
        <div class="form-group">
            <label class="control-label col-lg-3" for="description">descr</label>
            <div class="controls col-lg-6">
                <textarea rows="5" cols="50" id="description" ng-model="trainingInfo.training.description" class="form-control"></textarea>
            </div>
        </div>
...

Second form is identical but for the ng-submit attribute which is as follows: ng-submit="editTraining()"

I would be very grateful if someone who has met the same issue with AngularJs forms could suggest a best practice to me...

1 Answer 1

1

You can create a directive that uses the form as a template. The directive can bind to a submit function and use that in the template.

Directive:

app.directive('myForm', function () {
  return {
    restrict: 'E',
    template: '<form ng-submit="submit()"><button type="submit">Press me</button></form>',
    replace: true,
    scope:
    {
      submit: '&'
    }
  };
});

Usage:

<my-form submit="submitOne()"></my-form>
<my-form submit="submitTwo()"></my-form>

Simple demo: http://plnkr.co/edit/ERdxGJKrb9JRIWslMJkP?p=preview

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

1 Comment

Sounds great! Thanks a lot. I am going to try and test that and keep you posted!

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.