Reputation: 529
I want insert dynamic fields into a form.
For example: I have a field list like:
<input type="text" name="names[]" class="name-1">
<input type="text" name="names[]" class="name-2">
<input type="text" name="names[]" class="name-1">
In jQuery I only need serializate all form and send it, like $('#myForm').serialize().
But, I don't know how can I do this in angular.
Somebody have some idea?
In angular i only know use the directive ng-mode and I can't do that: ng-mode="myform.name[]"
Upvotes: 0
Views: 3052
Reputation: 529
I've found the solution and is to here:
/* -------------------------------------------------------
* Source: http://www.shanidkv.com/blog/angularjs-adding-form-fields-dynamically
* Author: Muhammed Shanid [email protected]
**********Thank's very mush Muhammed **********
* Hacked By: Wilowayne De La Cruz [email protected]
---------------------------------------------------------*/
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.fields = [{name: 'employed-name-1'}, {name: 'employed-name-2'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.fields.length + 1;
$scope.fields.push({'name':'employed-name-'+newItemNo});
};
$scope.removeChoice = function() {
var lastItem = $scope.fields.length-1;
$scope.fields.splice(lastItem);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="angularjs-starter" ng-controller="MainCtrl">
<fieldset data-ng-repeat="field in fields">
<input type="text" ng-model="field.value" name="" placeholder="Enter employe name">
<button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
</fieldset>
<button class="addfields" ng-click="addNewChoice()">Add fields</button>
<div id="choicesDisplay">
{{ fields }}
</div>
</div>
Upvotes: 2
Reputation:
Try something like this:
<form ng-submit="submitMyForm()">
<div class="form-group">
<label class="control-label ">Input1</label>
<input class="form-control" type="text" name="input1" ng-model="input1"/>
</div>
<div class="form-group">
<label class="control-label ">Input2</label>
<input class="form-control" type="text" name="input2" ng-model="input2"/>
</div>
</form>
Your angular controller could look like this:
app.controller('MyCtrl', ['$scope', function MyController ($scope) {
$scope.input1 = 'Pre-set value of input 1';
$scope.input2 = 'Pre-set value of input 2';
$submitMyForm = function()
{
console.log('input1 value: ' + $scope.input1);
console.log('input2 value: ' + $scope.input2);
}
}]);
Upvotes: 0
Reputation: 542
Angular is a data-model oriented framework. You can bind your model (ej: array of value) to view trhought ng-model and ng-repeat and so submit directly your binded model
Upvotes: 0