How to Increment Dynamic field ngModel name in Angularjs..? - angularjs

Here when i click Add Product Button it creates a text field. But I want to create create different name for each text box in ng-model="column.product_cgst".
like column.product_cgst-1, column.product_cgst-2.
<form>
<div ng-repeat="column in columns" style="margin-bottom: 10px;">
<div class="form-group">
<input type="text" name="product_name" ng-model="column.product_name" required placeholder="Product Name" class="form-control"
id="userName">
</div>
<div class="form-group">
<select name="units" ng-model="column.units" class="form-control">
<option value="">Select Units</option>
<option ng-repeat="units in allunits" value="{{units.unit_id}}">
{{units.unit_name}}
</option>
</select>
</div>
<div class="form-group">
<input id="cgst" type="text" ng-model="column.product_cgst" placeholder="Enter CGST" required class="form-control">
</div>
<div class="form-group">
<input id="sgst" type="text" ng-model="column.product_sgst" placeholder="Enter SGST" required class="form-control">
</div>
<div class="form-group">
<input id="igst" type="text" ng-model="column.product_igst" placeholder="Enter IGST" required class="form-control">
</div>
<button class="remove btn-sm btn-danger" ng-click="removeColumn($index)">x</button>
</div>
<div class="form-group text-right m-b-0">
<button class="btn btn-primary waves-effect waves-light" type="submit">
Submit
</button>
<button class="addfields btn btn-info waves-effect waves-light" ng-click="addProduct()">Add Product</button>
</div>
</form>
Controller:
$scope.columns = [];
$scope.addProduct = function () {
var newItemNo = $scope.columns.length + 1;
$scope.columns.push({ 'colId': 'col' + newItemNo });
};
$scope.removeColumn = function (index) {
$scope.columns.splice(index, 1);
if ($scope.columns.length() === 0 || $scope.columns.length() == null) {
alert('no rec');
$scope.columns.push = [{ "colId": "col1" }];
}
};

You can use $index in the HTML to increment your ng-model dynamically instead of doing in controller.
Using $index in the interpolation with ngModel will not work. Try something like below
column.product_cgst[$index]

I get the Solutions here,only change in my angularjs controllers.
//Add Dynamic Column
$scope.columns = [{id: 'firstField'}];
$scope.addProduct = function(){
var newItemNo = $scope.columns.length+1;
$scope.columns.push({'id':'field'+newItemNo});
}
//Remove Dynamic Column
$scope.removeColumn = function() {
var itemLast = $scope.columns.length-1;
$scope.columns.splice(itemLast);
};
//Insert Data in Database:-
$scope.productAdd = function(){
$http.post('product/insert_product', $scope.columns)
.success(function(data){
console.log(data);
});
}

Related

close bootstrap modal window using angularjs after submit

I'm creating an inventory app, and the user has the option to add a new product or edit an existing one. Both options bring up the same modal window, and I want it to close automatically after the user clicks on submit.
Below is part of my code, my entire code is here: http://codepen.io/andresq820/pen/LWGKXW
HTML
<div class="modal fade" id="editItemModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">{{title(item.code)}}</h4>
</div>
<div class="modal-body">
<form name="myEditForm" ng-submit="editProduct(item)">
<div class="form-group">
<label for="code">Code:</label>
<input type="text" size="5" maxlength="5" minlength="3" class="form-control" name="code" id="code"
ng-model="item.code" ng-disabled="false" ng-pattern="/^[a-zA-Z0-9]*$/">
<span ng-show="myEditForm.code.$error.pattern">Code can only be alphanumeric.</span> </br>
<span ng-show="myEditForm.code.$error.minlength">Code has to be at least 3 characters</span>
</div>
<div class="form-group">
<label for="description">Description:</label>
<input type="text" class="form-control" name="description" id="description" ng-model="item.description" required>
<span ng-show="myEditForm.description.$touched && myEditForm.description.$invalid">The description is required.</span>
</div>
<div class="form-group">
<label for="amount">Amount:</label>
<input type="number" class="form-control" name="amount" id="amount" size="5" maxlength="5"
ng-model="item.amount" ng-pattern="/^[0-9]{1,7}$/">
<span ng-show="myEditForm.amount.$error.pattern">Only whole numbers are allowed</span>
</div>
<div class="form-group">
<label for="newImage">{{loadImg}}</label>
<input type="file" class="form-control" name="newImage" id="newImage" ng-model="item.image">
</div>
<div class="form-group" ng-show="displayRadioBtns">
<label for="radio">Type:</label>
<div class="radio">
<label><input type="radio" name="optradio" ng-model="item.type" value="in">In</label>
<label><input type="radio" name="optradio" ng-model="item.type" value="out">Out</label>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Close" />
<input type="submit" class="btn btn-primary pull-right" value="Submit" ng-disabled="myEditForm.$invalid"/>
</div>
</form>
</div>
</div>
</div>
</div>
ANGULARJS
$scope.editProduct = function(item){
var index = $scope.items.indexOf(item);
console.log(index);
console.log(item);
console.log(item.code.valueOf());
if(index == -1){
console.log('new item');
$scope.item.code = item.code;
$scope.item.description = item.description;
$scope.item.in = item.amount;
$scope.item.out = 0;
$scope.item.createdOn = Date.now();
$scope.items.push($scope.item);
$scope.item = {};
}else{
console.log('edit item');
console.log(item);
console.log(item.type);
console.log($scope.item.type);
console.log(index);
$scope.items[index].code = item.code;
console.log($scope.items[index].code);
$scope.items[index].description = item.description;
console.log($scope.items[index].description);
$scope.items[index].image = item.image;
if($scope.item.type == 'in'){
console.log($scope.item.type);
console.log(typeof($scope.items[index].in));
console.log(typeof($scope.item.amount));
console.log(typeof(item.amount));
$scope.items[index].in += item.amount;
console.log($scope.items[index].in);
$scope.item = {};
}else if($scope.item.type == 'out'){
console.log($scope.item.type);
$scope.items[index].out += $scope.item.amount;
$scope.item = {};
}else{
alert("Type is a required field");
return;
};
}
};
You can make function calls on ngSubmit
form class="well" (ngSubmit)="addUserModal.hide(); addUser(model); userForm.reset()" #userForm="ngForm"
I haven't used AngularJS, but the following works for me in Angular 2, if you're able to use jQuery:
$(".modal").modal("hide")
Fire button click on submit event in angularJS.
<input id="quemodalcancel" type="submit" value="Cancel" class="btn blue_btn" data-dismiss="modal" aria-hidden="true">
$scope.editProduct = function(item){
// submit button code
document.querySelector('#quemodalcancel').click();
}

Can't get option value when using Angularjs

I have the following AngularJS code:
angular.module('loggedInApp', ['ui.bootstrap']);
var myapp = angular.module('loggedInApp', ['ui.bootstrap'])
myapp.controller('AddParentController', function ($scope, addParentService) {
var vm = this;
$scope.addParentService = addParentService;
$scope.setName = function (val) {
addParentService.inputParentName = val;
}
$scope.setEmail = function (val) {
addParentService.inputParentEmail = val;
}
$scope.setCarrier = function (val) {
addParentService.inputParentCarrier = val;
}
$scope.setBirthday = function (val) {
addParentService.inputParentBirthday = val;
}
});
myapp.service('addParentService', function () {
var vm = this;
vm.eventObjs = [];
vm.parent = [];
vm.addParent = function () {
alert(vm.inputParentName);
alert(vm.inputParentBirthday);
alert(vm.inputParentEmail);
alert(vm.inputParentCellPhone);
alert(vm.inputParentCarrier);
vm.parent.push({
name: vm.inputParentName, dob: vm.inputParentBirthday,
cell: vm.inputParentCellPhone, carrier: vm.inputParentCarrier,
email: vm.inputParentEmail, active: true, personId: vm.parent.length + 1
});
vm.inputParentName = '';
vm.inputParentDOB = '';
vm.inputParentCellPhone = '';
vm.inputParentCarrier = 0;
vm.inputParentEmail = '';
vm.active = true;
};
vm.buildEventObject = function (titleValue, startValue, personId, choreIdValue) {
vm.eventObjs.push({ title: titleValue, start: startValue, familymemberpersonid: personId, choreId: choreIdValue });
return vm.eventObjs;
}
vm.returnEventObject = function () {
return vm.eventObjs;
}
});
My HTML looks like this:
<div class="row clearfix" ng-controller="AddParentController as parent">
<div class="col-md-6 column">
<form role="form" ng-submit="addParentService.addParent()">
<div class="form-group">
<label for="inputParentName">Name</label><input class="form-control" id="inputParentName" value="" type="text" ng-model="addParentService.inputParentName" />
</div>
<div class="form-group">
<label for="inputParentBirthday">Birthday</label><input class="form-control" id="inputParentBirthday" value="" type="text" ng-model="addParentService.inputParentBirthday" />
</div>
<div class="form-group">
<label for="inputParentCellPhone">Cell Phone</label><input class="form-control" id="inputParentCellPhone" value="" type="text" ng-model="addParentService.inputParentCellPhone" />
</div>
<div class="form-group">
<label for="inputParentCarrier">Phone Carrier</label><br />
<select class="form-control" id="inputParentCarrier">
<option>ATT</option>
<option>Cricket</option>
<option>Sprint</option>
<option>T-Mobile</option>
<option>Verizon</option>
</select>
</div>
<div class="form-group">
<label for="inputParentEmail">E-Mail Address</label><input class="form-control" id="inputParentEmail" value="" type="email" ng-model="addParentService.inputParentEmail" />
</div>
<button class="btn btn-default" type="submit">Submit</button>
</form>
</div>
<br /><br />
<div class="col-md-6 column">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
Parent:
</h3>
</div>
<div class="panel-body">
<table class="table table-striped">
<tr>
<th>Name</th>
<th>Cell #</th>
<th>E-Mail</th>
<th>DOB</th>
</tr>
<tr ng-repeat="parent in addParentService.parent">
<td>{{parent.name}}</td>
<td>{{parent.cell}}</td>
<td>{{parent.email}}</td>
<td>{{parent.dob}}</td>
</tr>
</table>
</div>
<div class="panel-footer">
<button class="btn btn-default" type="submit">Save your Family!</button>
</div>
</div>
</div>
</div>
My issue is when I click the submit button I am calling my service that alerts out all the different values I entered. Everything works except the inputParentCarrier value. When it alerts out it says 'undefined'
Seems like this should be an easy fix, but right now I can't see what is wrong.
You are missing ng-model on your select
<select class="form-control" id="inputParentCarrier" ng-model="addParentService.inputParentCarrier">
<option>ATT</option>
<option>Cricket</option>
<option>Sprint</option>
<option>T-Mobile</option>
<option>Verizon</option>
</select>
You need to add ng-model="addParentService.inputParentCarrier" to your select tag
you need to add model for select element as well, like:
<select ng-model="addParentService.inputParentCarrier" class="form-control" id="inputParentCarrier">
<option>ATT</option>
<option>Cricket</option>
<option>Sprint</option>
<option>T-Mobile</option>
<option>Verizon</option>
</select>
You should bind your ng-model to the select, not the label.
<select class="form-control" id="inputParentCarrier" ng-model="addParentService.inputParentCarrier">
<option>ATT</option>
<option>Cricket</option>
<option>Sprint</option>
<option>T-Mobile</option>
<option>Verizon</option>
</select>
change your select tag to this:
<select class="form-control" id="inputCarrier" ng-model="myService.inputParentCarrier">
<option value="att">ATT</option>
....
<select>

AngularJs : Check some fields are valid then fire ajax and populate the select html

I've a form below
<form class="form-horizontal" role="form" name="req_appmt" id="req_appmt" novalidate ng-submit="SendAppointmentRequest()">
<div class="form-group" ng-class="(req_appmt.form_comments.$error.required) ? 'has-error' : '' ">
<label for="form_comments" class="col-lg-2 control-label">Reason for Appointment* :</label>
<div class="col-lg-10"><textarea id="form_comments" name="form_comments" ng-model="formdata.form_comments" class="form-control" rows="3" required></textarea></div>
</div>
<div class="form-group" ng-class="(req_appmt.physician_id.$error.required) ? 'has-error' : '' ">
<label for="physician_id" class="col-lg-2 control-label">To* :</label>
<div class="col-lg-10">
<select name="physician_id" ng-model="formdata.physician_id" id="physician_id" class="form-control" required>
<option value="">--Select--</option>
<option ng-repeat="physician in physicians" value="{{physician.id}}">{{physician.fullname}}</option>
</select>
</div>
</div>
<div class="form-group" ng-class="(req_appmt.date.$error.required) ? 'has-error' : '' ">
<label for="inputEmail1" class="col-lg-2 control-label">Date :</label>
<div class="col-lg-10">
<p class="input-group">
<input type="text" class="form-control" datepicker-popup="dd-MM-yyyy" ng-model="formdata.date" name="date" is-open="opened" min-date="minDate" close-text="Close" required="required" ng-click="open($event)">
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open($event)"><i class="glyphicon glyphicon-calendar"></i></button>
</span>
</p>
</div>
</div>
<div class="form-group" ng-class="(req_appmt.time.$error.required) ? 'has-error' : '' ">
<label for="inputEmail1" class="col-lg-2 control-label">Free Slot :</label>
<div class="col-lg-10">
<select name="time" ng-model="formdata.time" id="time" class="form-control" required>
<option value="">--Select--</option>
<!-- <option ng-repeat="key,value in slots" value="{{value}}">{{value}}</option> -->
</select>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10"><p>
<button type="submit" class="btn btn-primary btn-lg btn-success">Request Appointment</button>
Cancel
</p> </div> </div>
</form>
This is my controller :
ModuleEvents.controller('ctrlRequestAppointment', function ($location,$scope,$http,$rootScope,$cookies,ServiceCheckAuth,ServiceEvents){
/*First check patient is logged in*/
if( !ServiceCheckAuth.isPatientLoggedIn() ){
$location.url('/login');
return;
}
/*Set rootScope values*/
$rootScope.root = {
html_title:HTML_TITLE_PATIENT_APPOINTMENT_REQUEST,
loggedin:true,
activeNxtstp:'active',
customclass:'content_inner_im w-100-mob'
};
var json_physicians = localStorage.getItem('physicians');
$scope.minDate = $scope.minDate ? null : new Date();
$scope.date = new Date();
$scope.physicians = JSON.parse(json_physicians);
$scope.formdata = {};
$scope.opened = false;
$scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.$watch(req_appmt.date.$valid, function() {
if( req_appmt.date.$valid && req_appmt.physician_id.$valid ){
console.log($scope.formdata);
}
});
$scope.SendAppointmentRequest = function(){
if( $scope.req_appmt.$valid ){
console.log($scope.formdata);
}
}
});
What I'm trying :
1) User selects To field in the form
2) then user selects date field in the form
3) then I want to check in controller both are filled and validated
4) then I want to fire a ajax request that will populate the Free Slot field of he form
Problem :
I can not check whether the fields are valid
Any help is greatly appreciated
Thanks
can you use an function() which can validate all fields of formdata like
$scope.function_name=function()
{
var validatefalg=true;
if($scope.formdata.physician_id!='')
{
validatefalg=false;
return validatefalg;
}
else
{
return validatefalg;
}
}
I solve my problem with the help of #jyotsna :
if( $scope.req_appmt.physician_id.$valid && $scope.req_appmt.date.$valid ){}

Splice item out of ng-repeat array, when that item is clicked

I have an array of items that I'm repeating.
<li ng-repeat="lineItem in lineItems" class="bouncy-slide-left">
<div class="form-group col-sm-5 col-lg-2 col-xl-2 pad-right">
<label for="expenses">{{lineItem.labels.name}}Expense:</label>
<br>
<select name="expenses" ng-model="expense.name" class="form-control" style="width: 175px;">
<option value="{{expense.name}}" ng-repeat="expense in expenses">{{expense.name}}</option>
</select>
</div>
<div class="form-group col-sm-5 col-lg-2 col-xl-2 pad-right">
<label>Material Cost:</label>
<br>
<input type="text" ng-model="expense.cost" class="form-control" name="material" placeholder="5.00">
</div>
<div class="form-group col-sm-5 col-lg-2 col-xl-2 pad-right">
<label>Quantity:</label>
<br>
<input type="text" ng-model="expense.quantity" class="form-control" name="quantity" placeholder="5">
</div>
<div class="form-group col-sm-5 col-lg-2 col-xl-2 pad-right">
<label>Labor Rate:</label>
<br>
<input type="text" ng-model="expense.labor" class="form-control" name="labor" placeholder="20.00">
</div>
<div class="form-group col-sm-5 col-lg-2 col-xl-2 pad-right">
<label>Hours:</label>
<br>
<input type="text" ng-model="expense.hours" class="form-control" name="hours" placeholder="4">
</div>
<div class="form-group col-sm-5 col-lg-3 col-xl-2 pad-right">
<label>Responsible:</label>
<br>
<span>Renter</span>
<input type="radio" name="radio-1">
<span>Owner</span>
<input type="radio" name="radio-1">
</div>
<br>
<div class="col-sm-12 pad-right">
<span class="pad-right">Owner Total: {{ownerTotal}}</span>
<span class="pad-right">Renter Total: {{renterTotal}}</span>
</div>
<div class="col-sm-12 pad-right">
<button class="btn btn-primary btn-sm" ng-click="addExpense()"><i class="fa-check"></i>Add New Expense</button>
<button class="btn btn-primary btn-sm" ng-click="removeExpense($event)"><i class="fa-remove"></i>Remove Expense</button>
</div>
</li>
I have an array, an add method, and a remove method.
$scope.lineItems = [
{expense: 1}
];
//when button is clicked
//add a new blank object to the lineItems array
$scope.addExpense = function() {
var num = Math.random();
var item = {expense: num};
$scope.lineItems.push(item);
};
//when remove button is clicked
//remove the specific item that was clicked from the array
$scope.removeExpense = function($event) {
var elm = $event.currentTarget.parentElement.parentElement;
console.log(elm);
elm.remove();
//need to splice selected item OUT of the array
var i = ???
$scope.lineItems.splice(i, 1);
};
I've tried several things here. Most of the answers I've found just use indexOf, however the items are being dynamically generated by my model. So I don't know how to get an index of something that doesn't exist yet.
I've also tried some jQueryLite. I would love to just use something like : when $this is clicked, remove it from the dom. I can't seem to find the ANGULAR answer for that.
Instead of ng-click="removeExpense($event)" simply pass the lineItem, like ng-click="removeExpense(lineItem)". You can then find the lineItem in lineItems by indexOf
$scope.removeExpense = function(lineItem) {
var index = $scope.lineItems.indexOf(lineItem);
$scope.lineItems.splice(index, 1);
}
call removeExpense($index) on ng-click like:
<button class="btn btn-primary btn-sm" ng-click="removeExpense($index)"><i class="fa-remove"></i>Remove Expense</button>
and replace remove function with this code:
$scope.removeExpense = function(index) {
$scope.lineItems.splice(index, 1);
}

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);
};
}

Resources