Is it possible to use the ng-model on the form element and automatically generate an array of form inputs when submitted?
This is what I want to have happen (assume I have the ng-app and ng-controller tags already in the html and the proper controller function declared and an array called "contacts" I would like to add the form data to):
index.html:
...
<form ng-model = 'addData'>
<input ng-model = 'name' />
<input ng-model = 'phone' />
<button ng-submit = 'addContact()' />
</form>
controller.js:
$scope.addContact = function () {
$scope.contacts.push ($scope.addData);
The ideal would be if this would add a key:value array to the existing array like this: {"[ng-model descriptor from input field]":"[input from form]", "[ng-model descriptor from input field]":"[input from form]"}. For example, if the user inputs "John" and "
(800) 555-1212" it would automatically generate a form model object like this: {"name":"John", "phone":"
(800) 555-1212"}
If not already possible, what would be the best alternative. As it is, I currently have code like this:
controller.js:
$scope.addContact = function () {
var phone = $scope.phone;
var contact = {"name":name,"phone":phone};
which is not very handy when I have a large number of input fields within the form. Also, it requires me to hard code the keys separate from the input fields. Lastly, it makes for tedious and error prone future changes to the form, especially if we add or delete inputs.
Is there a way to make this work? If not, what is there a better way of doing it than the tedious way I am doing it now?