Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass arguments to ng-submit

Tags:

I'm new to Angular, and I have this simple form:

<form ng-submit="add()">
  <input type="text" name="field">
  <input type="submit" value="Submit">
</form>

I'd like to have input[name="field"] value as a parameter of add(). Is there any way to do that?

What I did so far is to assign ng-model="field" in the input and within add() look for $scope.field.

In the controller I have an array of items, and the add() function. The $scope.field is hanging around like an intermediate step to get the value of the input to add() that I shouldn'd need.

Am I missing something or is this Angular's way?

like image 611
jviotti Avatar asked May 16 '13 15:05

jviotti


2 Answers

I would modify TheHippo's answer a bit and pass field as an argument to add(). This is more of a code design choice, but I think it lends to more flexibility and better testing.

Html:

<div ng-controller="MyFormController">
  <form ng-submit="add(field)">
    <input type="text" name="field" ng-model="field" />
    <input type="submit" value="Submit" />
  </form>
</div>

JS:

app.controller('MyFormController', ['$scope', function(scope) {
   scope.add = function(field) { // <-- here is you value from the input 
     // ...
   };
}]);

And a little note: If you follow most AngularJS tutorials online where there is some list being managed, and new items are added to that list, you will almost always see one of these properties that tend to "hang around" (they're often named 'newItem' etc.). In a way, this is the AngularJS way :)

like image 100
jlb Avatar answered Sep 19 '22 05:09

jlb


Make a small change to you HTML:

<form ng-submit="add()">
  <input type="text" name="field" model="field">
  <input type="submit" value="Submit">
</form>

In the controller (/ directive) that holds the form:

app.controller('MyFormController', ['$scope', function(scope) {
   scope.add = function() {
     scope.field // <-- here is you value from the input 
   };
}]);

This is the easiest and intended way you can do this in angular.

You could start looking into writing a own directive / service that will do what you want to archive, but depending of the rest of you code, this might be the easiest and shortest way.

like image 23
TheHippo Avatar answered Sep 20 '22 05:09

TheHippo