Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

What is the "angular 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 its 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 docs).

share|improve this question
    
Use ng-change – New Dev Dec 21 '14 at 9:26

1 Answer 1

up vote 1 down vote accepted

Well you can do something like this for sure by triggering Angular 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

share|improve this answer
    
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? – Vera Wang Dec 21 '14 at 9:46
    
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({...}). – dfsq Dec 21 '14 at 9:53
    
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. – dfsq Dec 21 '14 at 9:55
    
Unfortunately I don't have a say in how I implement the ajax requests, I must obtain the query string. – Vera Wang Dec 21 '14 at 10:08
1  
Yes, in angular it's a little less convenient. There are different approaches. Take a look at this question: stackoverflow.com/questions/14514461/… – dfsq Dec 21 '14 at 10:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.