wmash
wmash

Reputation: 4202

Trigger ng-submit on ng-click

I am following this answer (and this fiddle) on how to accomplish this.

View:

<section>
    <form style="display: none" id="addFriendForm" name="vm.form.addFriendForm" class="form-horizontal" submit-on="submitAddFriendForm" ng-submit="vm.save(vm.form.addFriendForm.$valid)" novalidate>
        <input ng-model="vm.userInput" required>
    </form>
    <div class="list-group">
        <a ng-repeat="user in vm.users" ng-click="vm.triggerSubmit(user)" class="list-group-item">
            ...
        </a>
    </div>
</section>

Directive:

function submitOn() {
    return {
        link: function postLink(scope, element, attrs) {
            scope.$on(attrs.submitOn, function() {
                setTimeout(function() {
                    // Error:
                    element.trigger('submit');
                });
            });
        }
    };
}

Controller: (triggerSubmit)

// Trigger submit of the form
function triggerSubmit(user) {
    vm.userInput = user;
    $scope.$broadcast('submitAddFriendForm');
}

When walking through this, I get the error:

TypeError: element.trigger is not a function

...on the line highlighted in the directive. Looking at docs, this seems correct. What's the reason for it failing?

ANSWER: (if a jQuery answer is wanted, look at the answer below)

A pure angular way of doing it is:

angular.element(element).triggerHandler('submit');

Upvotes: 1

Views: 605

Answers (2)

wmash
wmash

Reputation: 4202

See the other answer for a jQuery approach. For a pure angular approach I used:

angular.element(element).triggerHandler('submit');

Upvotes: 1

Chanthu
Chanthu

Reputation: 1794

Looks like trigger is not a part of JQLite which ships with angular. You might have to load JQuery before loading angular.

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>

OR

As part of your build pipeline (grunt/gulp/webpack etc)

Upvotes: 1

Related Questions