AngularJS Form submit - angularjs

Working on my first small AngularJS App I'm facing problems with a form submit. I worked trough the CodeSchool course and figured the most out by myself, but this form submit thingy... well I just don't get where I'm wrong so that's why it would be nice if you could show me the right solution, so I can go on.
Project: A simple Workout List where you can list all the training sessions you had. This is my HTML, Element 3 is the problem:
<header class="wob-masthead container-fluid">
<div class="row">
<div class="col-md-6" ng-init="tab = 1">
<ul class="nav nav-pills">
<li ng-class="{ active:tab === 1 }"><a href ng-click="tab = 1">Overview</a></li>
<li ng-class="{ active:tab === 2}"><a href ng-click="tab = 2">Stats</a></li>
<li ng-class="{ active:tab === 3 }"><a href ng-click="tab = 3">New</a></li>
</ul>
</div>
<div class="col-md-6">
<form class="navbar-form pull-right" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
</div>
</div>
</header>
<section class="wob-main mainlist container" id="headjump">
<!--- ==========================================
Element 1: Overview
============================================= -->
<div class="subsite" ng-show="tab === 1">
<div class="headico"><span class="glyphicon glyphicon-signal" aria-hidden="true"></span></div>
<h1>WorkoutBuddy</h1>
<div class="table-responsive" ng-controller="ListController as listing">
<table class="table table-hover">
<thead>
<tr>
<th class="col-md-2">Date</th>
<th class="col-md-8">Type</th>
<th class="col-md-1">Repeat</th>
<th class="col-md-1">Time</th>
</tr>
</thead>
<tbody ng-controller="ListController as listing">
<tr ng-repeat="wo in listing.sessions">
<td>{{wo.date | date:'dd/MM/yyyy'}} </td>
<td>{{wo.name}}</td>
<td>{{wo.repeat}}</td>
<td>{{wo.time}} Minutes</td>
</tr>
</tbody>
</table>
</div>
</div>
<!--- ==========================================
Element 2: Stats
============================================= -->
<div class="subsite" ng-show="tab === 2">
<div class="headico"><span class="glyphicon glyphicon-signal" aria-hidden="true"></span></div>
<h1>Stats</h1>
<!-- Ende Subsite -->
</div>
<!--- ==========================================
Element 3: New
============================================= -->
<div class="subsite" ng-show="tab === 3">
<div class="headico"><span class="glyphicon glyphicon-signal" aria-hidden="true"></span></div>
<h1>New</h1>
<div class="table-responsive" ng-controller="ListController as listing">
<table class="table table-hover">
<thead>
<tr>
<th class="col-md-2">Date</th>
<th class="col-md-8">Type</th>
<th class="col-md-1">Repeat</th>
<th class="col-md-1">Time</th>
</tr>
</thead>
<tbody ng-controller="ListController as listing">
<tr ng-repeat="wo in listing.sessions | limitTo:2">
<td>{{wo.date | date:'dd/MM/yyyy'}} </td>
<td>{{wo.name}}</td>
<td>{{wo.repeat}}</td>
<td>{{wo.time}} minutes</td>
</tr>
</tbody>
</table>
</div>
<form name="WorkoutForm" ng-controller="EntryController as entryCtrl">
<blockquote>
<h3>Last Workout:</h3>
<strong>{{entryCtrl.wo.name}}</strong><br>
<small>am: {{entryCtrl.wo.date}}</small><br>
{{entryCtrl.wo.repeat}} repeats in {{wo.time}} minutes.
</blockquote>
<input ng-model="entryCtrl.wo.date" type="date" placeholder="date" />
<input ng-model="entryCtrl.wo.name" type="name" placeholder="name" />
<input ng-model="entryCtrl.wo.repeat" type="repeat" placeholder="repeat" />
<input ng-model="entryCtrl.wo.time" type="time" placeholder="time" />
<input type="submit" value="Add" />
</form>
<!-- Ende Subsite -->
</div>
</section>
I styled it with Bootstrap and this is my app.js:
(function(){
var app = angular.module('wobuddy', [ ]);
app.controller('ListController', function(){
this.sessions = wos;
});
var wos = [
{
name: 'Squat',
date: '01.01.2015',
repeat: 50,
time: 10
},
{
name: 'Push Ups',
date: '01.01.2015',
repeat: 50,
time: 10
}
];
})();
Switching between the sections using the nav works pretty fine and also printing out the data-elements in the table, but when I push submit nothing happens - really hope you can help me to learn :-)

You need to make an EntryController that will add a new object to the end of the wos collection. Something like this:
app.controller('EntryController', function($scope) {
$scope.wo = {};
$scope.submit = function() {
wos.push($scope.wo);
$scope.wo = {}; // Clear the form fields
};
});
Then your HTML for that section could look something like this:
<form name="WorkoutForm" ng-controller="EntryController">
<blockquote>
<h3>Last Workout:</h3>
<strong>{{wo.name}}</strong><br>
<small>am: {{wo.date}}</small><br>
{{wo.repeat}} repeats in {{wo.time}} minutes.
</blockquote>
<input ng-model="wo.date" type="date" placeholder="date" />
<input ng-model="wo.name" type="name" placeholder="name" />
<input ng-model="wo.repeat" type="repeat" placeholder="repeat" />
<input ng-model="wo.time" type="time" placeholder="time" />
<button ng-click="submit()">Add</button>
</form>
Notice that it's more usual for a controller to communicate data to the template via the $scope object rather than via the controller object itself.

By looking at you form HTML, I think you missed the name attribute inside your form and also ng-submit directive is missing which will gets called after a submit form. Do check form validation inside controller using $valid() method and perform post else give alert to user.
HTML
<form name="workoutForm" ng-controller="ReviewController as reviewCtrl" ng-submit="submit(workoutForm, entryCtrl.wo)">
<blockquote>
<h3>Last Workout:</h3>
<strong>{{entryCtrl.wo.name}}</strong>
<br>
<small>am: {{entryCtrl.wo.date}}</small>
<br> {{entryCtrl.wo.repeat}} repeats in {{wo.time}} minutes.
</blockquote>
<input name="date" ng-model="entryCtrl.wo.date" type="date" placeholder="date" />
<input name="name" ng-model="entryCtrl.wo.name" type="name" placeholder="name" />
<input name="repeat" ng-model="entryCtrl.wo.repeat" type="repeat" placeholder="repeat" />
<input name="time" ng-model="entryCtrl.wo.time" type="time" placeholder="time" />
<input type="submit" value="Add" />
</form>
Controller
$scope.submit = function(workoutForm, item){
if(workoutForm.$valid)
//then make $http.post by sending item values
else
//show error
};

UPDATE
<html ng-app='demoApp'>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<form ng-controller="validationCtrl">
<input type="text" placeholder="Name...." ng-model="user.name"/>
<input type="text" placeholder="Password...." ng-model="user.pass"/>
<input type="text" placeholder="Mobile...." ng-model="user.mo"/>
<input type="submit" ng-click="alldata(user)"/>
</form>
<script>
//This is controller
var app = angular.module('demoApp', []);
app.controller('validationCtrl', function($scope) {
$scope.alldata=function(user)
{
alert(JSON.stringify(user));
}
});
</script>
</body>
</html>

You can also use this method, and
Your form shoud be like
<form method="post" name="sentMessage" id="my_contact" novalidate="novalidate">
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2">
<label>Name</label>
<input class="form-control" id="name" type="text" name="name" placeholder="Name" required="required" data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2">
<label>Email Address</label>
<input class="form-control" id="email" type="email" name="email" placeholder="Email Address" required="required" data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2">
<label>Phone Number</label>
<input class="form-control" id="phone" type="tel" name="phone" placeholder="Phone Number" required="required" data-validation-required-message="Please enter your phone number.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2">
<label>Message</label>
<textarea class="form-control" id="message" rows="5" name="Message" placeholder="Message" required="required" data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<br>
<div id="success"></div>
<div class="form-group">
Send
</div>
</form
import jquery as below
npm install jquery using CLI
import * as $ from 'jquery';
send_query() function will be
send_query() {
var data = $("#my_contact").serializeArray();
var indxarr = {};
$.each(data,function(i,v){
indxarr[v['name']] = v['value'];
});
data = JSON.parse(JSON.stringify(indxarr))
//POST YOUR DATA
this.httpClient.post('http://localhost/rajat/ajax/contact_query_submit/', data,httpOptions)
.subscribe(data => {
console.log(data);
});
}
Your backend code will be
public function contact_query_submit(){
if ($this->input->post()) {
$postdata = file_get_contents("php://input");
$_POST = json_decode($postdata,TRUE);
$addArr = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'phone' => $this->input->post('phone'),
'message' => $this->input->post('message'),
'created' => time()
);
if($this->main_model->create('rjt_contact', $addArr)){
$arr[] = array('type' => 'success', 'msg' => '<p>Your query has been received. <br>We will get back to you soon.</p>');
echo json_encode($arr);
}else{
$arr[] = array('type' => 'warning', 'msg' => '<p>'.$this->db->last_query().'</p>');
echo json_encode($arr);
}
}else{
$arr[] = array('type' => 'warning', 'msg' => '<p>No data post yet</p>');
echo json_encode($arr);
}
}

Related

Validate form only if one or more field contains a number, Angular.JS

I want to validate an order form with Angular.JS.
The form dynamically adds input fields depending on how many products there are.
The dynamically added input fields are used to determine how many products the user wants to purchase.
I want the form to validate if either one of the fields has a value of minimum 1 (the user has to choose at least one product in order to send the form).
The issue I am having is that I cannot work out how the conditional validation "if one field has a value greater than 0 the form is valid".
If I put in min='1' as an attribute for the input field, both field needs to have a value of 1 in order for the form to work.
If I have a placeholder="0" the input fields has a value and therefore will validate the form as long as the other fields are valid.
My idea which I do not know how to implement (or if it's smart) is to check the products total sum is greater than 0.
Obviously I am a newbie and use a lot of resources online to implement functionality I want to have.
HTML
<form id="orderForm" name="orderForm" role="form" ng-submit="submitForm(orderForm.$valid)" class="orderForm" ng-controller="formController as formCtrl" novalidate>
<table class="table">
<thead>
<tr>
<th scope="col">Produkt</th>
<th scope="col">Antal</th>
<th scope="col" class="text-right">Pris</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="product in formCtrl.products">
<td>
<img ng-src="{{product.images.thumb}}" alt="{{product.name}}">
<h6 class="d-inline-block">{{product.name}} <small class="d-block">{{product.description}}</small></h6>
</td>
<td>
<input type="number" class="form-control" ng-model="product.quantity" name="{{'quantity' + product.productId}}" min="0" max="99" required>
</td>
<td class="text-right">
{{product.price | currency : "SEK"}}
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3" class="text-right">
<h5 class="d-inline-block">Totalt: <em ng-bind="sumCalc(product.price) | currency : 'SEK'"></em></h5>
</td>
</tr>
</tfoot>
</table>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="inputEmail">Email</label>
<input name="email" ng-model="formCtrl.email" type="email" class="form-control" id="inputEmail" placeholder="Email" required>
<div ng-show="orderForm.email.$invalid && !orderForm.email.$pristine" class="invalid-feedback">
Vänligen fyll i en korrekt email
</div>
</div>
<div class="col-md-4 mb-3">
<label for="inputFirstName">Förnamn</label>
<input name="firstname" ng-model="formCtrl.fName" type="text" class="form-control" id="inputFirstName" placeholder="Förnamn" required>
<div ng-show="orderForm.fName.$invalid && !orderForm.fName.$pristine" class="invalid-feedback">
Vänligen fyll i ditt förnamn
</div>
</div>
<div class="col-md-4 mb-3">
<label for="inputLastName">Efternamn</label>
<input name="lastname" ng-model="formCtrl.lName" type="text" class="form-control" id="inputLastName" placeholder="Efternamn" required>
<div ng-show="orderForm.lName.$invalid && !orderForm.lName.$pristine" class="invalid-feedback">
Vänligen fyll i ditt efternamn
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="inputStreet">Gatuadress</label>
<input name="street" ng-model="formCtrl.street" type="text" class="form-control" id="inputStreet" placeholder="Gatuadress" required>
<div ng-show="orderForm.street.$invalid && !orderForm.street.$pristine" class="invalid-feedback">
Vänligen fyll i din gatuaddress
</div>
</div>
<div class="col-md-4 mb-3">
<label for="inputZip">Postnr</label>
<input name="zip" ng-model="formCtrl.zip" type="text" class="form-control" id="inputZip" placeholder="Postnummer" required>
<div ng-show="orderForm.zip.$invalid && !orderForm.zip.$pristine" class="invalid-feedback">
Vänligen fyll i ditt postnummer
</div>
</div>
<div class="col-md-4 mb-3">
<label for="inputTown">Stad</label>
<input name="town" ng-model="formCtrl.town" type="text" class="form-control" id="inputTown" placeholder="Stad" required>
<div ng-show="orderForm.town.$invalid && !orderForm.town.$pristine" class="invalid-feedback">
Vänligen fyll i din stad
</div>
</div>
</div>
<div> orderForm is {{orderForm.$valid}}</div>
<div class="form-group">
<button type="submit" class="btn btn-default" id="inputSubmitButton" ng-disabled="orderForm.$invalid && inputQuantity.">Skicka</button>
</div>
</form>
controllers.js
var app = angular.module('controllers', []);
app.controller('formController', function($scope) {
this.products = product;
$scope.submitForm = function(isValid) {
// check to make sure the form is completely valid
if (isValid) {
alert('our form is amazing');
}
};
$scope.sumCalc = function() {
var sum = 0;
angular.forEach(product, function(product, index) {
sum += parseInt(product.quantity, 10) * product.price;
});
return sum;
//totalPrice = sum;
};
});
var product = [{
name: 'asd',
productId: 01,
price: 100,
description: 'asd',
specification: "asd",
images: {
full: 'asd',
thumb: 'asd'
},
quantity: 0
},
{
name: "asd",
productId: 02,
price: 100,
description: "asd",
specification: "asd",
images: {
full: 'asd',
thumb: 'asd'
},
quantity: 0
}
];
var app = angular.module('controllers', []);
app.controller('formController', function($scope) {
this.products = product;
$scope.submitForm = function(isValid) {
// check to make sure the form is completely valid
if (isValid) {
alert('our form is amazing');
}
};
$scope.sumCalc = function() {
var sum = 0;
angular.forEach(product, function(product, index) {
sum += parseInt(product.quantity, 10) * product.price;
});
return sum;
//totalPrice = sum;
};
});
var product = [{
name: 'asd',
productId: 01,
price: 100,
description: 'asd',
specification: "asd",
images: {
full: 'asd',
thumb: 'asd'
},
quantity: 0
},
{
name: "asd",
productId: 02,
price: 100,
description: "asd",
specification: "asd",
images: {
full: 'asd',
thumb: 'asd'
},
quantity: 0
}
];
Edit your HTML as following:
<form id="orderForm" name="orderForm" role="form" ng-submit="submitForm(orderForm.$valid)" class="orderForm" ng-controller="formController as formCtrl" novalidate>
<table class="table">
<thead>
<tr>
<th scope="col">Produkt</th>
<th scope="col">Antal</th>
<th scope="col" class="text-right">Pris</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="product in formCtrl.products">
<td>
<img ng-src="{{product.images.thumb}}" alt="{{product.name}}">
<h6 class="d-inline-block">{{product.name}} <small class="d-block">{{product.description}}</small></h6>
</td>
<td>
<input type="number" class="form-control" ng-model="product.quantity" name="{{'quantity' + product.productId}}" min="0" max="99" required>
</td>
<td class="text-right">
{{product.price | currency : "SEK"}}
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3" class="text-right">
<h5 class="d-inline-block">Totalt: <em ng-bind="sumCalc(product.price) | currency : 'SEK'"></em></h5>
</td>
</tr>
</tfoot>
</table>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="inputEmail">Email</label>
<input name="email" ng-model="formCtrl.email" type="email" class="form-control" id="inputEmail" placeholder="Email" required>
<div ng-show="orderForm.email.$invalid && !orderForm.email.$pristine" class="invalid-feedback">
Vänligen fyll i en korrekt email
</div>
</div>
<div class="col-md-4 mb-3">
<label for="inputFirstName">Förnamn</label>
<input name="firstname" ng-model="formCtrl.fName" type="text" class="form-control" id="inputFirstName" placeholder="Förnamn" required>
<div ng-show="orderForm.fName.$invalid && !orderForm.fName.$pristine" class="invalid-feedback">
Vänligen fyll i ditt förnamn
</div>
</div>
<div class="col-md-4 mb-3">
<label for="inputLastName">Efternamn</label>
<input name="lastname" ng-model="formCtrl.lName" type="text" class="form-control" id="inputLastName" placeholder="Efternamn" required>
<div ng-show="orderForm.lName.$invalid && !orderForm.lName.$pristine" class="invalid-feedback">
Vänligen fyll i ditt efternamn
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="inputStreet">Gatuadress</label>
<input name="street" ng-model="formCtrl.street" type="text" class="form-control" id="inputStreet" placeholder="Gatuadress" required>
<div ng-show="orderForm.street.$invalid && !orderForm.street.$pristine" class="invalid-feedback">
Vänligen fyll i din gatuaddress
</div>
</div>
<div class="col-md-4 mb-3">
<label for="inputZip">Postnr</label>
<input name="zip" ng-model="formCtrl.zip" type="text" class="form-control" id="inputZip" placeholder="Postnummer" required>
<div ng-show="orderForm.zip.$invalid && !orderForm.zip.$pristine" class="invalid-feedback">
Vänligen fyll i ditt postnummer
</div>
</div>
<div class="col-md-4 mb-3">
<label for="inputTown">Stad</label>
<input name="town" ng-model="formCtrl.town" type="text" class="form-control" id="inputTown" placeholder="Stad" required>
<div ng-show="orderForm.town.$invalid && !orderForm.town.$pristine" class="invalid-feedback">
Vänligen fyll i din stad
</div>
</div>
</div>
<div> orderForm is {{orderForm.$valid}}</div>
<div class="form-group">
<button type="submit" class="btn btn-default" id="inputSubmitButton" ng-disabled="orderForm.$invalid || !checkProductSelected()">Skicka</button> <!--Pay attention to the 'ng-disabled' binding-->
</div>
</form>
and modify your Javascript to look like this:
app.controller('formController', function($scope) {
this.products = product;
$scope.submitForm = function(isValid) {
// check to make sure the form is completely valid
if (isValid) {
alert('our form is amazing');
}
};
$scope.sumCalc = function() {
var sum = 0;
angular.forEach(product, function(product, index) {
sum += parseInt(product.quantity, 10) * product.price;
});
return sum;
//totalPrice = sum;
};
//***The following function is added to your original code***
$scope.checkProductSelected = function() {
var sum = 0;
angular.forEach(product, function(product, index) {
sum += parseInt(product.quantity, 10) * product.price;
});
return sum > 0;
}
});
Look for the comments in the code to see what has been added or edited. (On HTML it's after your submit button)

Why is the ng-show directive not working?

This is the form.
<div class="row" ng-controller="contactsCtrl">
<form ng-show="addFormShow">
<h3>Add Contact</h3>
<!-- Add form -->
<div class="row">
<div class="large-6 columns">
<label>Name:
<input type="text" ng-model="name" placeholder="Contact Name" required />
</label>
</div>
<div class="large-6 columns">
<label>Email:
<input type="text" ng-model="email" placeholder="Contact Email" required />
</label>
</div>
</div>
<div class="row">
<div class="large-6 columns">
<label>Company:
<input type="text" ng-model="company" placeholder="Company Name" required />
</label>
</div>
<div class="large-6 columns">
<label>Work Phone:
<input type="text" ng-model="work_phone" placeholder="Work Phone" required />
</label>
</div>
</div>
<div class="row">
<div class="large-6 columns">
<label>Mobile Phone:
<input type="text" ng-model="mobile_phone" placeholder="Mobile Phone" required />
</label>
</div>
<div class="large-6 columns">
<label>Home Phone:
<input type="text" ng-model="home_phone" placeholder="Home Phone" required />
</label>
</div>
</div>
<div class="row">
<div class="large-6 columns">
<label>Street Address:
<input type="text" ng-model="street_address" placeholder="Street Address" required />
</label>
</div>
<div class="large-6 columns">
<label>City:
<input type="text" ng-model="city" placeholder="City" required />
</label>
</div>
</div>
<div class="row">
<div class="large-6 columns">
<label>State:
<input type="text" ng-model="state" placeholder="State" required />
</label>
</div>
<div class="large-6 columns">
<label>Zip Code:
<input type="text" ng-model="zipcode" placeholder="Zip Code" required />
</label>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<input type="submit" value="Add Contact" class="button" />
</div>
</div>
</form>
<div class="large-10 columns">
<h3>Your Contacts (3)</h3>
<table>
<thead>
<tr>
<th width="200px">Name</th>
<th width="200px">Company</th>
<th width="25%">Email</th>
<th width="25%">Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="contact in contacts">
<td>{{contact.name}}</td>
<td>{{contact.company}}</td>
<td>{{contact.email}}</td>
<td><a class="button tiny" ng-click="showEditForm(contact)">Edit</a>
<a class="button tiny alert" ng-click="removeContact(contact)">Delete</a></td>
</tr>
</tbody>
</table>
</div>
<div class="small-12 large-2 columns">
<a class="button large" ng-click="showAddForm()">+</a>
</div>
</div>
This is the controller.
'use strict';
angular.module('myContacts.contacts', ['ngRoute','firebase'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/contacts', {
templateUrl: 'contacts/contacts.html',
controller: 'contactsCtrl'
});
}])
.controller('contactsCtrl', ['$scope', '$firebaseArray', function($scope,$firebaseArray) {
var ref = new Firebase('https://mycontacts-1bb2d.firebaseio.com/contacts');
$scope.contacts = $firebaseArray(ref);
$scope.showAddForm = function(){
$scope.addFormShow = true;
}
}]);
This is pretty simple code. Its supposed to show the form when the user clicks on the '+' button. But I cant figure out why the ng-show directive is not working.
It works fine with your code, check if you have properly added ng-controller in your code.
DEMO
var myApp = angular.module('ReqWebApp', [])
myApp.controller('contactsCtrl', function contactsCtrl($scope) {
$scope.showAddForm = function(){
$scope.addFormShow = true;
}
});
<!DOCTYPE html>
<html ng-app="ReqWebApp">
<head>
<meta charset="UTF-8">
<title>New Request</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="contactsCtrl">
<form ng-show="addFormShow">
<h3>Add Contact</h3>
<!-- Add form -->
<div class="row">
<div class="large-6 columns">
<label>Name:
<input type="text" ng-model="name" placeholder="Contact Name" required />
</label>
</div>
<div class="large-6 columns">
<label>Email:
<input type="text" ng-model="email" placeholder="Contact Email" required />
</label>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<input type="submit" value="Add Contact" class="button" />
</div>
</div>
</form>
<div class="small-12 large-2 columns">
<a class="button large" ng-click="showAddForm()">+</a>
</div>
</body>
</html>
The code works fine for me. I think you might have done some small error in adding controller. Refer the code below
<html ng-app='FormApp'>
<head>
</head>
<body ng-controller='contactsCtrl'>
<form ng-show="addFormShow">
<h3>Add Contact</h3>
<!-- Add form -->
<div class="row">
<div class="large-6 columns">
<label>Name:
<input type="text" ng-model="name" placeholder="Contact Name" required />
</label>
</div>
<div class="large-6 columns">
<label>Email:
<input type="text" ng-model="email" placeholder="Contact Email" required />
</label>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<input type="submit" value="Add Contact" class="button" />
</div>
</div>
</form>
<div class="small-12 large-2 columns">
<a class="button large" ng-click="showAddForm()">+</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<script>
angular.module('FormApp', []).controller('contactsCtrl', ['$scope', function($scope) {
$scope.showAddForm = function() {
$scope.addFormShow = true;
}
}]);
</script>
</body>
</html>

Angular Help List App

I'm creating an Angular app that adds info to a list but I can't seen to get the item to post. I want the use to add info to the form then the info is then add to the responsive table. I'm not sure if the function for the inputs are correct. Check out my code below.
angular.module('LumpSumApp', [])
.controller('LumpSumController', function() {
var lumpSumList = this;
lumpSumList.addLumpSum = function() {
lumpSumList.lumpsums.push({ select: lumpSumList.lumpSumType, done: false });
lumpSumList.lumpSumType = '';
lumpSumList.lumpsums.push({ select: lumpSumList.lumpSumCategory, done: false });
lumpSumList.lumpSumCategory = '';
lumpSumList.lumpsums.push({ text: lumpSumList.lumpSumEstimate, done: false });
lumpSumList.lumpSumEstimate = '';
lumpSumList.lumpsums.push({ text: lumpSumList.lumpSumExpenses, done: false });
lumpSumList.lumpSumExpenses = '';
lumpSumList.lumpsums.push({ file: lumpSumList.lumpSumQuote, done: false });
lumpSumList.lumpSumQuote = '';
lumpSumList.lumpsums.push({ file: lumpSumList.lumpSumReceipt, done: false });
lumpSumList.lumpSumReceipt = '';
};
});
<form class="form-inline" ng-submit="lumpSumList.addLumpSum()">
<div class="form-group">
<select class="form-control" ng-model="lumpSumList.lumpSumType">
<option>Select a Type</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<div class="form-group">
<select class="form-control" ng-model="lumpSumList.lumpSumCategory">
<option>Select a Category</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<div class="form-group">
<input class="form-control" type="text" ng-model="lumpSumList.lumpSumEstimate" size="40" placeholder="Estimated Expenses">
</div>
<div class="form-group">
<input class="form-control" type="text" ng-model="lumpSumList.lumpSumExpenses" size="40" placeholder="Actual Expenses">
</div>
<div class="form-group">
<label class="btn btn-primary">
<i class="fa fa-file-text-o" aria-hidden="true"></i>
<input type="file" ng-model="lumpSumList.lumpSumQuote" style="display: none;">
</label>
</div>
<div class="form-group">
<label class="btn btn-primary">
<i class="fa fa-file-text-o" aria-hidden="true"></i>
<input type="file" ng-model="lumpSumList.lumpSumReceipt" style="display: none;">
</label>
</div>
<input class="btn btn-primary" type="submit" value="add">
</form>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Expense Type</th>
<th>Expense Category</th>
<th>Estimated Expenses</th>
<th>Actual Expenses</th>
<th>Upload Quote(s)</th>
<th>Upload Receipt(s)</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="lumpsum in lumpSumList.lumpsums">
<td>{{lumpSumList.lumpSumType}}</td>
<td>{{lumpSumList.lumpSumCategory}}</td>
<td>{{lumpSumList.lumpSumEstimate}}</td>
<td>{{lumpSumList.lumpSumExpenses}}</td>
<td>{{lumpSumList.lumpSumQuote}}</td>
<td>{{lumpSumList.lumpSumReceipt}}</td>
</tr>
</tbody>
</table>
</div>
I reworked your code with changes to handle an array of objects.
The two keys here are the changes to the controller code and the changes to the HTML.
In the JavaScript, we first initialize the lumpSumList.lumpsums when the controller loads. Then, inside the function, each time the addLumpSum button is clicked, we create a new object to hold all the properties from the dropdowns, then push this object into the array.
In the HTML, we output the lumpsum values, rather than the dropdown values. Just as a quick fix, I also added value='' to the default options in the dropdown to get rid of the empty option.
angular.module('LumpSumApp', [])
.controller('LumpSumController', function() {
var lumpSumList = this;
lumpSumList.lumpsums = [];
lumpSumList.addLumpSum = function() {
var lumpsum = {
lumpSumType: lumpSumList.lumpSumType,
lumpSumCategory: lumpSumList.lumpSumCategory,
lumpSumEstimate: lumpSumList.lumpSumEstimate,
lumpSumExpenses: lumpSumList.lumpSumExpenses
};
lumpSumList.lumpsums.push(lumpsum);
lumpSumList.lumpSumType = '';
lumpSumList.lumpSumCategory = '';
lumpSumList.lumpSumEstimate = '';
lumpSumList.lumpSumExpenses = '';
};
});
<!DOCTYPE html>
<html ng-app="LumpSumApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script src="app.js"></script>
</head>
<body ng-controller="LumpSumController as lumpSumList">
<form class="form-inline" ng-submit="lumpSumList.addLumpSum()">
<div class="form-group">
<select class="form-control" ng-model="lumpSumList.lumpSumType">
<option value=''>Select a Type</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<div class="form-group">
<select class="form-control" ng-model="lumpSumList.lumpSumCategory">
<option value=''>Select a Category</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<div class="form-group">
<input class="form-control" type="text" ng-model="lumpSumList.lumpSumEstimate" size="40" placeholder="Estimated Expenses">
</div>
<div class="form-group">
<input class="form-control" type="text" ng-model="lumpSumList.lumpSumExpenses" size="40" placeholder="Actual Expenses">
</div>
<div class="form-group">
<label class="btn btn-primary">
<i class="fa fa-file-text-o" aria-hidden="true"></i>
<input type="file" ng-model="lumpSumList.lumpSumQuote" style="display: none;">
</label>
</div>
<div class="form-group">
<label class="btn btn-primary">
<i class="fa fa-file-text-o" aria-hidden="true"></i>
<input type="file" ng-model="lumpSumList.lumpSumReceipt" style="display: none;">
</label>
</div>
<input class="btn btn-primary" type="submit" value="add">
</form>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Expense Type</th>
<th>Expense Category</th>
<th>Estimated Expenses</th>
<th>Actual Expenses</th>
<th>Upload Quote(s)</th>
<th>Upload Receipt(s)</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="lumpsum in lumpSumList.lumpsums">
<td>{{lumpsum.lumpSumType}}</td>
<td>{{lumpsum.lumpSumCategory}}</td>
<td>{{lumpsum.lumpSumEstimate}}</td>
<td>{{lumpsum.lumpSumExpenses}}</td>
<td>{{lumpsum.lumpSumQuote}}</td>
<td>{{lumpsum.lumpSumReceipt}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>

How to post dynamic form data in angularjs?

Am new to angularjs, i need to http post the dynamic form data to an API.
app.js
$scope.contacts = [
{ 'cpName':'',
'cpDesignation':'' ,
'cpDept': '',
'cpEmail': '',
'cpMobile':''
}
];
$scope.addRow = function(){
$scope.contacts.push({ 'cpName':$scope.cpName, 'cpDesignation': $scope.cpDesignation, 'cpDept':$scope.cpDept, 'cpEmail':$scope.cpEmail, 'cpMobile':$scope.cpMobile});
$scope.cpName='';
$scope.cpDesignation='';
$scope.cpDept='';
$scope.cpEmail='';
$scope.cpMobile='';
};
contact form
<form name="myform" role="form" ng-submit="addRow()">
<div class="row" ng-class="{true: 'error'}[submitted && myform.cpEmail.$invalid]">
<div class="form-group">
<label class="col-md-2 control-label">CONTACT PERSON</label>
<div class="col-md-4">
<input type="text" class="form-control" name="cpName"
ng-model="cpName" />
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">DESIGNATION</label>
<div class="col-md-4">
<input type="text" class="form-control" name="cpDesignation"
ng-model="cpDesignation" />
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">DEPARTMENT</label>
<div class="col-md-4">
<input type="text" class="form-control" name="cpDept"
ng-model="cpDept" />
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">EMAIL*</label>
<div class="col-md-4">
<input type="email" class="form-control" name="cpEmail"
ng-model="cpEmail" />
<span style="color:red" ng-show="myform.cpEmail.$dirty && myform.cpEmail.$invalid">
<span ng-show="myform.cpEmail.$error.required">Email is required.</span>
<span ng-show="myform.cpEmail.$error.email">Invalid email address.</span>
</span>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">MOBILE</label>
<div class="col-md-4">
<input type="number" class="form-control" name="cpMobile"
ng-model="cpMobile" />
</div>
</div>
<div class="form-group">
<div style="padding-left:110px">
<input type="submit" value="Add" class="btn btn-primary"/>
</div>
</div>
</div>
</form>
<table>
<tr>
<th>CONTACT PERSON</th>
<th>DESIGNATION</th>
<th>DEPARTMENT</th>
<th>EMAIL</th>
<th>Mobile</th>
</tr>
<tr ng-repeat="contact in contacts">
<td>{{contact.cpName}} </td>
<td>{{contact.cpDesignation}} </td>
<td>{{contact.cpDept}} </td>
<td>{{contact.cpEmail}} </td>
<td>{{contact.cpMobile}} </td>
</tr>
</table>
I know how to handle a single form data but not dynamic data.. Any help will be appreciated.
Thank you
Use ng-repeat over the rows.. So, in starting your $scope.contacts has 1 row and hence it will show one row in html.. Now push new object to $scope.contacts and then 2 rows will come in UI.
So, now just by pushing empty object to $scope.contacts you can get any number of rows.
Don't worry about the data every row will maintain its own data in the $scope.contacts array .. and at last just send this object to server. So, now you have dynamic rows.
Define your form like this
<div class="row" ng-repeat="contact in contacts">
<div class="form-group">
<label class="col-md-2 control-label">CONTACT PERSON</label>
<div class="col-md-4">
<input type="text" class="form-control" name="cpName"
ng-model="contact.cpName" />
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">DESIGNATION</label>
<div class="col-md-4">
<input type="text" class="form-control" name="cpDesignation"
ng-model="contact.cpDesignation" />
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">DEPARTMENT</label>
<div class="col-md-4">
<input type="text" class="form-control" name="cpDept"
ng-model="contact.cpDept" />
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">EMAIL*</label>
<div class="col-md-4">
<input type="email" class="form-control" name="cpEmail"
ng-model="contact.cpEmail" />
<span style="color:red" ng-show="myform.cpEmail.$dirty && myform.cpEmail.$invalid">
<span ng-show="myform.cpEmail.$error.required">Email is required.</span>
<span ng-show="myform.cpEmail.$error.email">Invalid email address.</span>
</span>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">MOBILE</label>
<div class="col-md-4">
<input type="number" class="form-control" name="cpMobile"
ng-model="contact.cpMobile" />
</div>
</div>
<div class="form-group">
<div style="padding-left:110px">
<input type="submit" value="Add" class="btn btn-primary"/>
</div>
</div>
</div>
<input type="button" value="Add" class="btn btn-primary" ng-click="upload()"/>
<table>
<tr>
<th>CONTACT PERSON</th>
<th>DESIGNATION</th>
<th>DEPARTMENT</th>
<th>EMAIL</th>
<th>Mobile</th>
</tr>
<tr ng-repeat="contact in contacts">
<td>{{contact.cpName}} </td>
<td>{{contact.cpDesignation}} </td>
<td>{{contact.cpDept}} </td>
<td>{{contact.cpEmail}} </td>
<td>{{contact.cpMobile}} </td>
</tr>
</table>
Here's your controller code
$scope.contacts = [{}];
$scope.upload = function(){
//api call
}
$scope.addRow = function(){
$scope.contacts.push({});
};

Refresh a table on pushing value into array

I am trying to display a table with data from an array in the controller. The html has a few input fields and on clicking submit I store the values in the input fields to the array. I then want to display the values in the table. I use ng-repeat on the tr.
I want the table to refresh and show the nwe data in the array. I am new to angularjs and I think the table should automatically show the new data because of ng-repeat. I'm not sure. If not, how do I refresh the table to show the new values.
But I think the problem is not that, because I added a few values to the array before pushing from the input fields, but the table still doesn't show my hard-coded array data.
The html(the table with ng-repeat is at the bottom and ng-controller at the top ):
<div class="content rows" ng-controller="mainController" >
<div class="navigationClass col-md-2"> <!-- Navigation DIv-->
<ul class="navColor nav nav-pills nav-stacked">
<li ><a style="color:#ffffff" href="#">Masters</a></li>
<li >Transactions</li>
<li ><a style="color:#ffffff" href="#">Reports</a></li>
<li ><a style="color:#ffffff" href="#">Devices</a></li>
<li class="active"><a style="color:#ffffff" href="#">Employees</a></li>
<li ><a style="color:#ffffff" href="#">Dashboard</a></li>
<li ><a style="color:#ffffff" href="#">Vendors</a></li>
</ul>
</div>
<div class="middle col-md-9 borderClass">
<div class="middle-header borderClass" style="padding-top:15px;padding-bottom:5px;">
<p style="text-align:center;color:#ffffff;">
Employee Registeration
</p>
</div>
<div class="">
<div class="createNewEmployee row" style="padding:5px;">
<div class="emptyDiv col-md-1"></div>
<div class="col-md-4">
<label class="marginClass" for="empId">Enter Employee ID</label>
<input ng-model="employeeID" type="text" id="empId" class="form-control marginClass" placeholder="Employee ID" name="">
<label for="empName" class="marginClass">Enter Employee name</label>
<input ng-model="employeeName" type="text" class="form-control marginClass" placeholder="Employee name" name="">
<label for="empCard" class="marginClass">Enter employee card number</label>
<input ng-model="employeeCardNumber" type="text" id="empCard" class="form-control marginClass" placeholder="Card number" name="">
<label for="doj" class="marginClass">Select employee DOJ</label>
<input ng-model="scopeDoj" type="text" id="doj" class="form-control marginClass" placeholder="DOJ" name="">
</div>
<div class="emptyDiv col-md-1"></div>
<div class="col-md-4">
<div class="form-group">
<label class="marginClass" for="categoryDropdown">Select category</label>
<select ng-model="employeeCategory" class="form-control marginClass" id="categoryDropdown">
<option>Company employee</option>
<option>Contract workman</option>
<option>Manager</option>
</select>
</div>
<div class="form-group">
<label class="marginClass" for="departmentDropdown">Select deparment</label>
<select ng-model="employeeDepartment" class="form-control marginClass" id="departmentDropdown">
<option>Pulp mill(Operation)</option>
<option>Stock preparation</option>
<option>Paper machine(Operation)</option>
<option>Finishing house</option>
<option>Paper machine(O)-V</option>
<option>SFT Street-C</option>
</select>
</div>
<div class="[ form-group ]" style="margin:5px; margin-top:25px;">
<input type="checkbox"
ng-model="activeOrInactive"
ng-true-value="'active'"
ng-false-value="'inactive'"
name="fancy-checkbox-default" id="activeID" autocomplete="off" />
<div class="[ btn-group ]">
<label class="" for="activeID">
Employee active
</label>
</div>
</div>
<div class="[ form-group ]" style="margin:5px; margin-top:25px;">
<input type="checkbox"
ng-model = "fingerprintActiveOrInactive"
ng-true-value="'fingeractive'"
ng-false-value="'fingerinactive'"
style="" name="fancy-checkbox-default" id="fingerprintActiveID" autocomplete="off" />
<div class="[ btn-group ]">
<label class="" for="fingerprintActiveID">
Fingerprint bio status active
</label>
</div>
</div>
</div>
<div class="emptyDiv col-md-2">
</div>
</div>
<p style="text-align:center"><button ng-click="addNewEmployee()" class="btn btn-primary">Submit</button></p>
</div>
<form class="form-inline" style="margin:20px;">
<div class="searchEmployee">
<div class="form-group">
<p>
<label class="marginClass" for="searchBox">Search employee</label>
<input id="searchBox" type="text" class="form-control" placeholder="Type here to search" name="">
</p>
</div>
</div>
</form>
<div class = "theTable" style="border:1px thin #ff0000;">
<table class="table table-hover table-bordered" style="margin-bottom:1px;">
<thead>
<th>Employee ID</th>
<th>Employee name</th>
<th>Card number</th>
<th>DOJ</th>
<th>Department</th>
<th>Category</th>
<th>Status</th>
<th>Edit/Delete</th>
</thead>
<tbody>
<tr ng-repeat="employee in newEmployeeArray">
<td>{{employee.empid}}</td>
<td>{{employee.empname}}</td>
<td>{{employee.empcardnumber}}</td>
<td>{{employee.doj}}</td>
<td>{{employee.empcategory}}</td>
<td>{{employee.empdepartment}}</td>
<td>{{employee.empactive}}</td>
<td>{{employee.empfingerprint}}</td>
<td><a title="Edit" href="#" style="text-align:center;text-decoration:none">
<span class="glyphicon glyphicon-pencil"></span></a><a title="Edit" href="#">
<span title="Delete" class="glyphicon glyphicon-trash"></span></a></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
The controller:
var app = angular.module('itc-app', ['ngRoute']);
app.controller('mainController',function($scope,$route,$timeout){
$scope.employeeID="";
$scope.employeeName="";
$scope.employeeCardNumber="";
$scope.scopeDoj="";
$scope.employeeCategory="Company employee";
$scope.employeeDepartment="Pulp mill(Operation)";
$scope.activeOrInactive="inactive";
$scope.fingerprintActiveOrInactive = "fingerinactive";
// $scope.newEmployeeScopeArray;
var newEmployeeArray = [
{
empid:'a',empname:'a',empcardnumber:'',doj:'',
empcategory:'',empdepartment:'',empactive:'',
empdepartment:'',empactive:'',empfingerprint:'',
empty:''
}
];
$scope.addNewEmployee = function(){
$timeout(function(){
newEmployeeArray.push({
empid:$scope.employeeID,
empname:$scope.employeeName,
empcardnumber:$scope.employeeCardNumber,
doj:$scope.scopeDoj,
empcategory:$scope.employeeCategory,
empdepartment:$scope.employeeDepartment,
empactive:$scope.activeOrInactive,
empfingerprint:$scope.fingerprintActiveOrInactive,
empty:''
});
// $route.reload();
$scope.employeeID="";
$scope.employeeName="";
$scope.employeeCardNumber="";
$scope.scopeDoj="";
$scope.activeOrInactive="inactive";
$scope.fingerprintActiveOrInactive = "fingerinactive";
console.log(newEmployeeArray);
},1000);
}
})
You just forgot to add newEmployeeArrayto your controllers $scope. When you do that, than pushing a new entry to that array will automatically update your view via ng-repeat.
newEmplyoeeArray is not visible from the $scope. You need to write
$scope.newEmployeeArray = [
{
empid:'a',empname:'a',empcardnumber:'',doj:'',
empcategory:'',empdepartment:'',empactive:'',
empdepartment:'',empactive:'',empfingerprint:'',
empty:''
}
];
instead of var newEmployeeArray.
Two things:
1) Please use the $scope for newEmployeeArray ($scope.newEmployeearray = .....)
Only the variable in the scope are watched for changes. That's the reason your view is not getting updated when the array is updated
2) You don't need to put the newEmployeeArray.push... inside the $timeout. $timeout would wait for the cycle to be completed and then push which would again change the scope and start a new cycle. This would hamper the performance.

Resources