8

What is the "AngularJS way" of doing a form submit when any of its inputs have been clicked (or changed)?

<form ng-submit="submit($event)" id="myForm">
  <input type="checkbox" name="foo" value="bar" ng-click="???"/>
</form>

I'm tempted to use jQuery and simply doing ng-click="$('#myForm').submit()", but it's probably worth learning it properly.

I have tried doing ng-click="submit($event)", but the error here is the $event object within the scope of the input instead of the entire form (correct me if I'm wrong, this is what I'm getting from the documentation).

0

2 Answers 2

4

Well, you can do something like this for sure by triggering the AngularJS submit event:

$scope.change = function($event) {
    $timeout(function() {
        angular.element($event.target.form).triggerHandler('submit');
    });
};

where

<input type="checkbox" name="foo" value="bar" ng-click="change($event)" />

However I think it's better to simply use the same function in ngClick as used in ngSubmit.

Demo: http://plnkr.co/edit/tJIYD9ZVjYzwA2aXJobo?p=preview

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

7 Comments

Trying this now, quick question: I'm trying to log the query string for the form (i.e. ?foo=bar) in my $scope.submit function. In jQuery I would use $(event.currentTarget).serialize();. How would I console.log the query string using plain angular/jQLite?
Why do you need it? If you plan to send data with AJAX call then $http service will serialize data for you from the object. If you use jQuery you can still use $.param({...}).
Make sure you use ngModel directive on your input elements, like <input type="checkbox" name="foo" ng-model="model.check" value="bar" ng-click="change($event)" /> <input type="text" ng-model="model.name">, etc. Then you will be able to access model data as $scope.model - will give you an object of data, which you can send to backend using $http.
Unfortunately I don't have a say in how I implement the ajax requests, I must obtain the query string.
Yes, in angular it's a little less convenient. There are different approaches. Take a look at this question: stackoverflow.com/questions/14514461/…
|
1

ng-change is what worked for me using a text input:

<form>
    <select data-ng-model="headerName" data-ng-options="header for header in headers"
            data-ng-change="calculateCorrelations()"></select>
</form>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.