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?
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 :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With