How to submit form with multiple inputs with the same name - angularjs

I have a form with three input fields and function to add new row:
<form ng-submit="">
<fieldset data-ng-repeat="person in persons">
<input type="text" ng-model="username">
<input type="text" ng-model="house">
<input type="text" ng-model="points">
</fieldset>
<button ng-click="addNewChoice()">Add fields</button><input type="submit" value="Submit">
</form>
And then I try to print data and its empty.
<div id="choicesDisplay">
{{ persons }}
</div>
js part:
$scope.persons = [];
$scope.addNewChoice = function() {
var newItemNo = $scope.persons.length + 1;
$scope.persons.push({
'username': "",
'house': "",
'points': "",
});
};
$scope.removeChoice = function() {
var lastItem = $scope.persons.length-1;
$scope.persons.splice(lastItem);
};
How is it possible to submit form as an array? I cant use username[]. Thank you

Need to user <input type="text" ng-model="person.username">
html:
<form ng-submit="">
<fieldset data-ng-repeat="person in persons">
<input type="text" ng-model="person.username">
<input type="text" ng-model="person.house">
<input type="text" ng-model="person.points">
</fieldset>
<button ng-click="addNewChoice()">Add fields</button><input type="submit" value="Submit">
</form>
And then I try to print data and its empty.
<div id="choicesDisplay">
{{ persons }}
</div>
js part:
$scope.persons = [];
$scope.addNewChoice = function() {
var newItemNo = $scope.persons.length + 1;
$scope.persons.push({
'username': "",
'house': "",
'points': "",
});
};
$scope.removeChoice = function() {
var lastItem = $scope.persons.length-1;
$scope.persons.splice(lastItem);
};

Related

How to post data to mongodb with dynamically generated fields using Angular js & Node.js

I am developing product upload page.
Few fields are fixed & few fields will be generated based on user selection, and then entire data will be posted to mongoDb.
Model
var productsSchema = new Schema({
merchantId: {type: String, required: true},
productName: {type: String, required: true},
productDescription: {type: String, required: true},
productStock: [
{
price: {type: Number, required: true},
color: {type: String, required: true},
}
],
offerFromMerchant: {
offerStartDate: {type: Date, required: false},
offerEndDate: {type: Date, required: false},
discountPercent: {type: Number, required: false}
}
});
Dynamically field generator controller method-Angular js
$scope.choices = [];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
if(lastItem > 0){
$scope.choices.splice(lastItem);
}
};
HTML
<div class="col-12">
<form ng-submit="addProducts()">
<fieldset data-ng-repeat="choice in choices">
<div class="form-group">
<hr>
<h3>Attributes</h3>
<div class="form-group">
<label>Price</label>
<input type="text" class="form-control" ng-model="product.productStock.price" placeholder="Enter price">
</div>
<div class="form-group">
<label>Color</label>
<input type="text" class="form-control" ng-model="product.productStock.color" placeholder="Enter color">
</div>
</fieldset>
<button type="submit" class="btn btn-primary">Add Product</button>
</form>
<button class="addfields" ng-click="addNewChoice()">Add fields</button>
</div>
</form><br/>
POST method-Angular js
$scope.addProducts = function () {
$http.post('/products/createProduct', $scope.product).then(function (res) {
console.log($scope.product);
});
}
I am trying to POST data with multiple attributes, but in database only single entry is present .
So the problem is, I don't know how to send $scope.choices with $scope.product, because some of the fields will be binding to $scope.product, and attributes field will be binding to $scope.choices.So how can I Post this kind of data to web-service ?
Please help..
You can directly bind the choice of color and and size to $scope.product by structuring it the way you want. So initialise productStock key of $scope.product to an array by $scope.product.productStock= [];. That way your object will be created in the desired way because of two way data binding.
HTML:
<div class="col-12">
<form ng-submit="addProducts()">
<fieldset data-ng-repeat="val in product.productStock">
<div class="form-group">
<hr>
<h3>Attributes</h3>
<div class="form-group">
<label>Price</label>
<input type="text" class="form-control" ng-model="val.price" placeholder="Enter price">
</div>
<div class="form-group">
<label>Color</label>
<input type="text" class="form-control" ng-model="val.color" placeholder="Enter color">
</div>
</fieldset>
<button type="submit" class="btn btn-primary">Add Product</button>
</form>
<button class="addfields" ng-click="addNewChoice()">Add fields</button>
</div>
</form><br/>
JS:
$scope.product.productStock= [];
$scope.addNewChoice = function() {
var newItemNo = $scope.product.productStock.length+1;
$scope.product.productStock.push({price:'',color:''});
};
$scope.removeChoice = function() {
var lastItem = $scope.product.productStock.length-1;
if(lastItem > 0){
$scope.product.productStock.splice(lastItem);
}
};
$scope.addProducts = function () {
console.log($scope.product)
$http.post('/products/createProduct', $scope.product).then(function (res) {
});
}
You can initialize the object in the following way
$scope.product={
productName:YourProductValue,
productDescription:YourDescriptionValue,
productStock:[]
};

Edit Input name value

I'm adding form elements dynamically using AngularJS as you can see below and it works very fine.
But sometimes, the user need to change the value of the placeholder and replace it with a value with his choice and I don't see if it's possible or not ?
Here is my HTML
<div ng-app="angularjs-starter" ng-controller="MainCtrl">
<fieldset data-ng-repeat="choice in choices">
<div class="col-xs-3">
<div class="input-group">
<span class="input-group-addon">Tr.</span>
<input id="tr-dpa" class="form-control" placeholder="Enter mobile number">
<button class="remove" ng-click="removeChoice()">-</button>
</div>
</div>
</fieldset>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-1">
<button type="submit" class="add" ng-click="addNewChoice()">
+
</button>
</div>
</div>
</div>
And my script,
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.choices = [{id: 'choice1'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
jsfiddle
You should have your choices array like this:
$scope.choices = [{
id: 'choice1',
placeholder: 'Enter Mobile Number'
}];
And, inside ng-repeat,
<input id="tr-dpa" class="form-control" placeholder="{{choice.placeholder}}">
Now, when you add new input, ask for a placeholder and push it along with id.
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length + 1;
$scope.choices.push({
'id': 'choice' + newItemNo,
placeholder: $scope.placeholder
});
$scope.placeholder = "sample placeholder"
};
And, $scope.placeholder would be in HTML,
<input type="text" value="sample placeholder" ng-model="placeholder">
<button type="submit" class="add" ng-click="addNewChoice()">
+
</button>
working example

How to track two dimentional array data using Angularjs

I am new to Angularjs. I learned some basic concepts and I started developing a form. According to my requirements, I have to give 4 textboxes and if user wants wants more he adds another 4 textboxes. Meanwhile, I am unable to track the entered details.
// create angular app
var validationApp = angular.module('validationApp','');
// create angular controller
validationApp.controller('mainController', function($scope) {
$scope.choices = [{id: 'choice1'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.showChoiceLabel = function (choice) {
return choice.id === $scope.choices[0].id;
};
$scope.removeChoice = function() {
if($scope.choices.length>1){
var newItemNo = $scope.choices.length-1;
$scope.choices.pop();
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="validationApp" ng-controller="mainController">
<div class="form-group" data-ng-repeat="choice in choices">
<label for="choice" ng-show="showChoiceLabel(choice)">Family Details</label>
<input type="text" ng-model="choice.name" name="id.family_name" class="form-control" placeholder="Enter Family Memeber Name" size="20">
<input type="text" ng-model="choice.relation" name="id.family_relation" class="form-control" placeholder="Enter Relation" size="15">
<input type="text" ng-model="choice.age" name="id.family_age" class="form-control" placeholder="Enter Age" size="5">
<input type="text" ng-model="choice.qualification" name="id.family_qualification" class="form-control" placeholder="Enter Qualification" size="15">
<br/><button ng-show="$last" ng-click="addNewChoice()" class="btn btn-success">Add another member</button>
<button ng-show="$last" ng-click="removeChoice()" class="btn btn-danger">Remove field</button>
</div>
</div>
You have had an error in your initialisation of your app. The empty array in angular.module('validationApp', []). This array is the list of modules myApp depends on:
var validationApp = angular.module('validationApp',[]);
Further information in the docs.
// create angular app
var validationApp = angular.module('validationApp', []);
// create angular controller
validationApp.controller('mainController', function($scope) {
$scope.choices = [{id: 'choice1'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length + 1;
$scope.choices.push({id:'choice' + newItemNo});
};
$scope.showChoiceLabel = function(choice) {
return choice.id === $scope.choices[0].id;
};
$scope.removeChoice = function() {
if($scope.choices.length > 1) {
var newItemNo = $scope.choices.length - 1;
$scope.choices.pop();
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="validationApp" ng-controller="mainController">
<div class="form-group" data-ng-repeat="choice in choices">
<label for="choice" ng-show="showChoiceLabel(choice)">Family Details</label>
<input type="text" ng-model="choice.name" name="id.family_name" class="form-control" placeholder="Enter Family Memeber Name" size="20">
<input type="text" ng-model="choice.relation" name="id.family_relation" class="form-control" placeholder="Enter Relation" size="15">
<input type="text" ng-model="choice.age" name="id.family_age" class="form-control" placeholder="Enter Age" size="5">
<input type="text" ng-model="choice.qualification" name="id.family_qualification" class="form-control" placeholder="Enter Qualification" size="15">
<br/><button ng-show="$last" ng-click="addNewChoice()" class="btn btn-success">Add another member</button>
<button ng-show="$last" ng-click="removeChoice()" class="btn btn-danger">Remove field</button>
</div>
</div>

Fields values generated using ng-repeat is not getting while submit

Template for form submission. This page will display the form template. Initially it shows the TItle,Full Name. On clicking the 'Add Tags' link new input fields is been generated for entering tags.
On submit, the field input(story.tag) is not been included on RequestPayload
<form novalidate ng-submit="save()">
<div>
<label for="title">Title</label>
<input type="text" ng-model="story.title" id="title" required/>
</div>
<div>
<label for="firstName">Full Name</label>
<input type="text" ng-model="story.fullname" id="fullname" required/>
</div>
<div ng-controller="Note" >
<div ng-repeat="story in items ">
<label>Tag {{$index+1}}:</label>
<input type="text" ng-model="story.tag" id="tag" required/>
</div>
<a ng-click="add()">Add Tags</a>
</div>
<button id="save" class="btn btn-primary">Submit Story</button>
</form>
script :- app.js
angular.module("getbookmarks", ["ngResource"])
.factory('Story', function ($resource) {
var Story = $resource('/api/v1/stories/:storyId', {storyId: '#id'});
Story.prototype.isNew = function(){
return (typeof(this.id) === 'undefined');
}
return Story;
})
.controller("StoryCreateController", StoryCreateController);
function StoryCreateController($scope, Story) {
$scope.story = new Story();
$scope.save = function () {
$scope.story.$save(function (story, headers) {
toastr.success("Submitted New Story");
});
};
}
//add dynamic forms
var Note = function($scope){
$scope.items = [];
$scope.add = function () {
$scope.items.push({
inlineChecked: false,
tag: "",
questionPlaceholder: "foo",
text: ""
});
};
}
The story object inside ng-repeat is in another scope. This JSFiddle should do what you are looking for.
<div ng-app>
<div ng-controller="NoteCtrl">
<form novalidate ng-submit="save()">
<div>
<label for="title">Title</label>
<input type="text" ng-model="story.title" id="title" required/>
</div>
<div>
<label for="firstName">Full Name</label>
<input type="text" ng-model="story.fullname" id="fullname" required/>
</div>
<div ng-repeat="story in items">
<label>Tag {{$index+1}}:</label>
<input type="text" ng-model="story.tag" required/>
</div> <a ng-click="add()">Add Tags</a>
<button id="save" class="btn btn-primary">Submit Story</button>
</form>
<div ng-repeat="test in items">
<label>Tag {{$index+1}}: {{test.tag}}</label>
</div>
</div>
</div>
The NoteController:
function NoteCtrl($scope) {
$scope.story = {};
$scope.items = [];
$scope.story.tag = $scope.items;
$scope.add = function () {
$scope.items.push({
inlineChecked: false,
tag: "",
questionPlaceholder: "foo",
text: ""
});
console.log($scope.story);
};
}

AngularJS select not updating after json push

I have the following controller:
function userControl($scope,$http) {
$scope.users = [
{"id":"0","name":"User1","roles":[{}]},
{"id":"1","name":"User2","roles":[{}]},
]
$scope.addUser = function() {
var nextid = $scope.getNextId();
$scope.users.push({id:nextid,name:$scope.userName});
$scope.userName = '';
//$apply();
};
$scope.getNextId = function() {
var count = 0;
angular.forEach($scope.users, function(data) {
count = data.id;
});
var count2 = parseInt(count)+1;
return count2;
};
}
And the following HTML:
<h2>Users</h2>
<div ng-controller="userControl">
<div ng-repeat="user in users">
{{user.id}} : {{user.name}}
</div>
<form ng-submit="addUser()">
<input type="text" ng-model="userName" placeholder="User Name" />
<input type="submit" value="add">
</form>
</div>
<h2>Add role to user</h2>
<div ng-controller="userControl">
<div ng-repeat="user in users">
<u>{{user.id}} : {{user.name}}</u><br />
<div ng-repeat="role in user.roles">
{{role.name}}
</div>
<br />
</div>
<form ng-submit="addRoleToUser()">
<select ng-model="selectedUser" name="userSelect" ng-options="user.id as user.name for user in users"></select>
<input type="submit" value="add">
</form>
</div>
When I add a user in the addUser() function I can see the user is added since it's listed under the ng-repeat, however the user name does not appear in the select box.
This is because you use the same controller twice. This creates two separate scopes. When you add a user in one scope it doesn't get added in the second scope. The fix is simple, join the code in one scope:
<div ng-controller="userControl">
<h2>Users</h2>
<div>
<div ng-repeat="user in users">
{{user.id}} : {{user.name}}
</div>
<form ng-submit="addUser()">
<input type="text" ng-model="userName" placeholder="User Name" />
<input type="submit" value="add">
</form>
</div>
<h2>Add role to user</h2>
<div>
<div ng-repeat="user in users">
<u>{{user.id}} : {{user.name}}</u><br />
<div ng-repeat="role in user.roles">
{{role.name}}
</div>
<br />
</div>
<form ng-submit="addRoleToUser()">
<select ng-model="selectedUser" name="userSelect" ng-options="user.id as user.name for user in users"></select>
<input type="submit" value="add">
</form>
</div>
</div>
An alternative approach is to create a Service since services are singletons:
module.factory('Users',function(){
var users = [
{"id":"0","name":"User1","roles":[{}]},
{"id":"1","name":"User2","roles":[{}]},
];
return {
users:users,
add:function(user){
users.push(user);
}
}
});
function userControl($scope, Users) {
$scope.users = Users.users;
$scope.addUser = function() {
var nextid = $scope.getNextId();
Users.add({id:nextid,name:$scope.userName});
$scope.userName = '';
};
$scope.getNextId = function() {
var count = 0;
angular.forEach($scope.users, function(data) {
count = data.id;
});
var count2 = parseInt(count)+1;
return count2;
};
}
This will work with your original markup.

Resources