How to modify and update data table row in angular js? - javascript

I m learning of angular js and i have found i issue .
I m creating a new projects .
i have some button edit , add, remove,
if i click to my edit button than show all field but i want to show only current field than i click to update update this filed .
My code is here
Anguar
var app = angular.module('addApp', []);
app.controller('modifyCtrl', ['$scope', function($scope){
$scope.tabelsData= [
{'name':'rohit', 'dob':'15-august-1985', 'emailId':'rohit#rohit.com', 'phone':'9999999999', 'address':'Delhi Rohini', 'id':'0' },
{'name':'aman', 'dob':'26-july-1975', 'emailId':'haryanat#hr.com', 'phone':'9874563210', 'address':'Haryana Sonepat', 'id':'1' },
{'name':'devraj', 'dob':'27-march-1980', 'emailId':'punjab#punjab.com', 'phone':'7410258963', 'address':'Punjab AmritSar', 'id':'2' }
];
$scope.modify = function(tableData){
$scope.modifyField = true;
$scope.viewField = true;
};
$scope.update = function(tableData){
$scope.modifyField = false;
$scope.viewField = false;
};
}]);
HTML Code is
<div ng-app="addApp">
<div class="wraper" ng-controller="modifyCtrl">
<table>
<thead>
<tr>
<th>Name:</th>
<th>Date Of Birth</th>
<th>Email Id</th>
<th>Phone No.</th>
<th>Address</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="tableData in tabelsData"><form>
<td>
<div ng-hide="viewField">{{tableData.name | uppercase}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.name" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.dob}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.dob" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.emailId}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.emailId" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.phone}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.phone" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.address}}</div>
<div ng-show="modifyField">
<textarea ng-model="tableData.address"></textarea>
</div>
</td>
<td>
<button ng-hide="viewField" ng-click="modify(tableData)">Modify</button>
<button ng-show="modifyField" ng-click="update(tableData)">Update</button>
<button ng-hide="viewField">Add</button>
<button ng-hide="viewField">Remove</button>
</td></form>
</tr>
</tbody>
</table>
</div>
</div>
var app = angular.module('addApp', []);
app.controller('modifyCtrl', ['$scope', function($scope){
$scope.tabelsData= [
{'name':'rohit', 'dob':'15-august-1985', 'emailId':'rohit#rohit.com', 'phone':'9999999999', 'address':'Delhi Rohini', 'id':'0' },
{'name':'aman', 'dob':'26-july-1975', 'emailId':'haryanat#hr.com', 'phone':'9874563210', 'address':'Haryana Sonepat', 'id':'1' },
{'name':'devraj', 'dob':'27-march-1980', 'emailId':'punjab#punjab.com', 'phone':'7410258963', 'address':'Punjab AmritSar', 'id':'2' }
];
$scope.modify = function(tableData){
$scope.modifyField = true;
$scope.viewField = true;
};
$scope.update = function(tableData){
$scope.modifyField = false;
$scope.viewField = false;
};
}]);
table td, table th{
border:solid 1px red;
padding:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="addApp">
<div class="wraper" ng-controller="modifyCtrl">
<table>
<thead>
<tr>
<th>Name:</th>
<th>Date Of Birth</th>
<th>Email Id</th>
<th>Phone No.</th>
<th>Address</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="tableData in tabelsData"><form>
<td>
<div ng-hide="viewField">{{tableData.name | uppercase}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.name" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.dob}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.dob" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.emailId}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.emailId" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.phone}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.phone" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.address}}</div>
<div ng-show="modifyField">
<textarea ng-model="tableData.address"></textarea>
</div>
</td>
<td>
<button ng-hide="viewField" ng-click="modify(tableData)">Modify</button>
<button ng-show="modifyField" ng-click="update(tableData)">Update</button>
<button ng-hide="viewField">Add</button>
<button ng-hide="viewField">Remove</button>
</td></form>
</tr>
</tbody>
</table>
</div>
</div>

If you only want one row to show the inputs on clicking its respective modify button you have two options:
1) Attach booleans to each of the JSON indexes of the tabelsData array.
2) Make a mirror array that houses these booleans.
Having two separate booleans in this case is useless, because each one is being treated on a toggle basis:
Here is the core code for doing approach number two since I assume you want your data to remain the same:
JS:
$scope.editingData = {};
for (var i = 0, length = $scope.tabelsData.length; i < length; i++) {
$scope.editingData[$scope.tabelsData[i].id] = false;
}
$scope.modify = function(tableData){
$scope.editingData[tableData.id] = true;
};
$scope.update = function(tableData){
$scope.editingData[tableData.id] = false;
};
Html:
<tbody>
<tr ng-repeat="tableData in tabelsData">
<td>
<div ng-hide="editingData[tableData.id]">{{tableData.name | uppercase}}</div>
<div ng-show="editingData[tableData.id]"><input type="text" ng-model="tableData.name" /></div>
</td>
<td>
<div ng-hide="editingData[tableData.id]">{{tableData.dob}}</div>
<div ng-show="editingData[tableData.id]"><input type="text" ng-model="tableData.dob" /></div>
</td>
<td>
<div ng-hide="editingData[tableData.id]">{{tableData.emailId}}</div>
<div ng-show="editingData[tableData.id]"><input type="text" ng-model="tableData.emailId" /></div>
</td>
<td>
<div ng-hide="editingData[tableData.id]">{{tableData.phone}}</div>
<div ng-show="editingData[tableData.id]"><input type="text" ng-model="tableData.phone" /></div>
</td>
<td>
<div ng-hide="editingData[tableData.id]">{{tableData.address}}</div>
<div ng-show="editingData[tableData.id]">
<textarea ng-model="tableData.address"></textarea>
</div>
</td>
<td>
<button ng-hide="editingData[tableData.id]" ng-click="modify(tableData)">Modify</button>
<button ng-show="editingData[tableData.id]" ng-click="update(tableData)">Update</button>
<button ng-hide="viewField">Add</button>
<button ng-hide="viewField">Remove</button>
</td>
</tr>
</tbody>
I made an example:
http://plnkr.co/edit/lXq1WB

Here is an example in Angular2, (this will NOT work for AngularJS!)
fichier.html:
<ng2-toasty [position]="'top-left'"></ng2-toasty>
<label for="trainingInput" class="mr-2">{{ 'LABEL.FORMATION' | translate }} :</label>
<table class="table table-hover table-striped table-sortable table-bordered">
<thead>
<tr>
<th *ngFor="let column of columns" [class]="selectedClass(column.variable)" (click)="changeSorting(column.variable)" translate>
{{column.display}}
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let object of data | orderBy : convertSorting(); let rowIndex = index">
<td *ngFor="let column of columns" class="{{column.variable}}-td">
<div *ngIf="!toUpdates[object['id']]" >{{object[column.variable] | format: column.filter}}</div>
<div *ngIf="toUpdates[object['id']]"><input type="text" [(ngModel)]="object[column.variable]" ></div>
</td>
<td class="text-center">
<i *ngIf="!toUpdates[object['id']]" class="fa fa-pencil-square-o edit-formation" aria-hidden="true" (click) = "editFormation(object)"></i>
<i *ngIf="toUpdates[object['id']]" class="fa fa-check-square-o save-edit-form" (click)="updateFormation(object)"></i>
<i class="fa fa-times" aria-hidden="true" (click)="deleteFormation(object['id'])"></i>
</td>
</tr>
<tr [hidden]="isDisabled()">
<td><input type="text" class="form-control" placeholder="Année" #years></td>
<td><input type="text" class="form-control" placeholder="Formation" #label></td>
<td><input type="text" class="form-control" placeholder="Durée" #duration></td>
<td class="text-center align-middle">
<i class="fa fa-plus-circle fa-2x" (click)="addFormation(years.value, label.value, duration.value)"></i>
</td>
</tr>
</tbody>
</table>
fichier.ts:
import {Component, Injector, Input, OnChanges, OnInit} from '#angular/core';
import { Http, Headers, RequestOptions, URLSearchParams } from '#angular/http';
import DynamicComponent from '../dynamic-component';
import Formation from './formation';
import {ToastyService, ToastyConfig, ToastOptions, ToastData} from 'ng2-toasty';
#Component({
moduleId: module.id,
selector: 'formations-selector',
templateUrl: './formations-template.html',
styleUrls: ['./formations-template.css'],
})
export default class FormationsComponent{
candidate: any = null;
listFormations: any = null;
candidateDetails: any = null;
columns: any[];
sort: any;
data: any[];
toUpdates: {};
constructor(private injector: Injector, private http: Http,private toastyService: ToastyService, private toastyConfig: ToastyConfig) {
this.candidateDetails = this.injector.get('candidateDetails');
this.candidate = this.candidateDetails.candidate;
this.listFormations = this.candidateDetails.listFormations;
this.columns = this.listFormations.columns;
this.sort = this.listFormations.sort;
this.data = this.listFormations.data;
this.toastyConfig.theme = 'material';
this.toUpdates = {};
}
ngAfterViewInit(){
$(document).ready(function() {
/*
$('.edit-formation').click(function () {
var dad = $(this).parent().parent();
dad.find('td .duration-span').hide();
dad.find('td.duration-td').append('<input type="text" class="form-control" placeholder="Durée" value="'+dad.find('td .duration-span').html()+'" id = "duration-update" #durationu>');
dad.find('td .label-span').hide();
dad.find('td.label-td').append('<input type="text" class="form-control" placeholder="Formation" id="label-update" value="'+dad.find('td .label-span').html()+'" #labelu>');
dad.find('td .years-span').hide();
dad.find('td.years-td').append('<input type="text" class="form-control" placeholder="Année" id="years-update" value="'+dad.find('td .years-span').html()+'" #yearsu>');
dad.find('td.years-td').append('<i class="fa fa-check-square-o save-edit-form hidden" (click)="updateFormation(1, years.value, label.value, durationu)"></i>');
dad.find('td .edit-formation').addClass("hidden");
dad.find('td .save-edit-form').removeClass("hidden");
});
*/
/*
$('.save-edit-form').click(function () {
var dad = $(this).parent().parent();
dad.find('td .save-edit-form').addClass("hidden");
dad.find('td .edit-formation ').removeClass("hidden");
dad.find('td .duration-span').show();
$('#duration-update').remove();
dad.find('td .label-span').show();
$('#label-update').remove();
dad.find('td .years-span').show();
$('#years-update').remove();
});
*/
});
}
//Action déclenché lors d'un changement de société du candidat : on met à jour la liste des métiers associés
onChangeCompaniesInput(value) {
}
isDisabled(isDisabled) {
//return (isDisabled || !this.candidateDetails.isUserAuthorized) ? true : false;
}
selectedClass(columnName): string{
return columnName == this.sort.column ? 'sort-' + this.sort.descending : '';
}
changeSorting(columnName): void{
var sort = this.sort;
if (sort.column == columnName) {
sort.descending = !sort.descending;
} else {
sort.column = columnName;
sort.descending = false;
}
}
convertSorting(): string{
return this.sort.descending ? '-' + this.sort.column : this.sort.column;
}
onChangeMainFormaion(value): void{
console.log(value);
}
deleteFormation(idFormation): void{
let headers = new Headers('Content-Type', 'application/json');
let params: URLSearchParams = new URLSearchParams();
this.http.post('/api/formations/'+idFormation+'/deleteFormation', params).toPromise()
.then(
res =>
{
if(res.status == 200){
this.toastyService.success({
title: "Success",
msg: "La formation a etait supprmié avec Succès",
showClose: true,
timeout: 5000,
theme: 'default',
});
}else{
this.toastyService.error({
title: "Error",
msg: "Une erreur est survenue, veuillez réessayer ultérieurement",
showClose: true,
timeout: 5000,
theme: 'default',
});
}
}
).catch(this.handleError);
}
editFormation(tableData): void{
this.toUpdates[tableData['id']]= true;
}
updateFormation(tableData): void {
this.toUpdates[tableData['id']]= false;
console.log(tableData);
}
addFormation(years: string, label: string, durration: string, main: boolean = false): void{
let headers = new Headers('Content-Type', 'application/json');
let params: URLSearchParams = new URLSearchParams();
params.append('years', years);
params.append('label', label);
params.append('durration', durration);
params.append('main', main);
//let formation = new Formation(years, label, durration, false);
return this.http.post('/api/formations/'+this.candidate.id+'/addFormation', params).toPromise()
.then(
res =>
{
if(res.status == 200){
this.toastyService.success({
title: "Success",
msg: "La formation a etait ajouter avec Succès",
showClose: true,
timeout: 5000,
theme: 'default',
});
}else{
this.toastyService.error({
title: "Error",
msg: "Une erreur est survenue, veuillez réessayer ultérieurement",
showClose: true,
timeout: 5000,
theme: 'default',
});
}
}
).catch(this.handleError);
}
private handleError(error: any) {
let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Promise.reject(errMsg);
}
}

Related

Angular-6 based on the select inputbox and select dropdown not showing properly

This question is maybe asked, but that is not solving my issue.
The drop-down of key contains database, desktop and account. Based on the drop-down of key the value drop-down and inputbox will be changed.
https://stackblitz.com/edit/angular-ivy-zahevb?file=src%2Fapp%2Fapp.component.html
My issue: When I click 1st row it seems good.
But when I move on to 2nd row the data append not properly. And when I select account previuos row drop-down also changed as inputbox
Eg:
In 1st row I select Database,value should append ['mysql', 'oracle', 'mongo'] in drop-down
In 2nd row I select Desktop, value should append ['dell', 'lenovo', 'hp']
In 3rd row I select Account the inputbox will show
app.component.ts
import { Component, VERSION } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
dynamicArray: Array<any> = [];
newDynamic: any = {};
dbValue = ["mysql", "oracle", "mongo"];
desktopValue = [{'id':'1', 'name':'dell'}, {'id':'2', 'name':'lenovo'}, {'id':'3', 'name':'hp'}];
isdbShow:boolean = false;
isdesktopShow:boolean = false;
isaccountShow:boolean = false;
ngOnInit(): void {
this.newDynamic = { title1: "", title2: "", dropdownDataDb: [], dropdownDataDesktop: [] };
this.dynamicArray.push(this.newDynamic);
}
addRow(index) {
this.newDynamic = { title1: "", title2: "", dropdownDataDb: [], dropdownDataDesktop: [] };
this.dynamicArray.push(this.newDynamic);
console.log(this.dynamicArray);
return true;
}
deleteRow(index) {
if (this.dynamicArray.length == 1) {
return false;
} else {
this.dynamicArray.splice(index, 1);
return true;
}
}
changed(value, index) {
let dropdownDataDb;
let dropdownDataDesktop;
if (value == 1) {
this.isdbShow = true;
this.isdesktopShow = false;
this.isaccountShow = false;
this.dynamicArray[index].dropdownDataDb = this.dbValue;
}
if (value == 2) {
this.isdbShow = false;
this.isdesktopShow = true;
this.isaccountShow = false;
this.dynamicArray[index].dropdownDataDesktop = this.desktopValue;
}
if (value == 3) {
this.isdbShow = false;
this.isdesktopShow = false;
this.isaccountShow = true;
}
}
}
app.componet.html
<div class="container" style="margin-top: 5%">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Action</th>
<th>key</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let dynamic of dynamicArray; let i = index;">
<td (click)="deleteRow(i)">
<i class="fa fa-trash fa-2x"></i>
</td>
<td>
<select [(ngModel)]="dynamicArray[i].title1" class="form-control" #sel (change)="changed(sel.value, i)">
<option [value]='1'>Database</option>
<option [value]='2'>Desktop</option>
<option [value]='3'>Account</option>
</select>
</td>
<td>
<!-- show db data -->
<select *ngIf="isdbShow" [(ngModel)]="dynamicArray[i].title2" class="form-control">
<option *ngFor="let data of dynamicArray[i].dropdownDataDb;">{{data}}</option>
</select>
<!-- show desktop data -->
<select *ngIf="isdesktopShow" [(ngModel)]="dynamicArray[i].title2" class="form-control">
<option *ngFor="let data of dynamicArray[i].dropdownDataDesktop;">{{data?.name ? data?.name : data}}</option>
</select>
<!-- show account data -->
<input *ngIf="isaccountShow" type="text" [(ngModel)]="dynamicArray[i].title2" class="form-control">
</td>
</tr>
<tr>
<td (click)="addRow(0)">
<i class="fa fa-plus fa-2x"></i>
</td>
</tr>
</tbody>
</table>
</div>
ts code
dynamicArray: Array<any> = [];
newDynamic: any = {};
dbValue = ["mysql", "oracle", "mongo"];
desktopValue = [
{ id: "1", name: "dell" },
{ id: "2", name: "lenovo" },
{ id: "3", name: "hp" }
];
ngOnInit(): void {
this.newDynamic = {
title1: "",
title2: "",
dropdownDataDb: [],
dropdownDataDesktop: [],
isDropDown: true
};
this.dynamicArray.push(this.newDynamic);
}
addRow(index) {
this.newDynamic = {
title1: "",
title2: "",
dropdownDataDb: [],
dropdownDataDesktop: [],
isDropDown: true,
isText: false
};
this.dynamicArray.push(this.newDynamic);
console.log(this.dynamicArray);
return true;
}
deleteRow(index) {
if (this.dynamicArray.length == 1) {
return false;
} else {
this.dynamicArray.splice(index, 1);
return true;
}
}
changed(value: any, index: any) {
console.log(this.dynamicArray[index].title1);
if (value == 1) {
this.dynamicArray[index].isDropDown = true;
this.dynamicArray[index].isText = false;
this.dynamicArray[index].dropdownDataDb = this.dbValue;
}
if (value == 2) {
this.dynamicArray[index].isDropDown = true;
this.dynamicArray[index].isText = false;
this.dynamicArray[index].dropdownDataDesktop = this.desktopValue;
}
if (value == 3) {
this.dynamicArray[index].isDropDown = false;
this.dynamicArray[index].isText = true;
}
}
<div class="container" style="margin-top: 5%">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Action</th>
<th>key</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let dynamic of dynamicArray; let i = index;">
<td (click)="deleteRow(i)">
<i class="fa fa-trash fa-2x"></i>
</td>
<td>
<select [(ngModel)]="dynamicArray[i].title1" class="form-control" #sel (change)="changed(sel.value, i)">
<option [value]='1'>Database</option>
<option [value]='2'>Desktop</option>
<option [value]='3'>Account</option>
</select>
</td>
<td>
<!-- show db data -->
<select *ngIf="dynamicArray[i].title1 == 1 && dynamic?.isDropDown" [(ngModel)]="dynamicArray[i].title2" class="form-control">
<option *ngFor="let data of dynamicArray[i].dropdownDataDb;">{{data}}</option>
</select>
<!-- show desktop data -->
<select *ngIf="dynamicArray[i].title1 == 2 && dynamic?.isDropDown" [(ngModel)]="dynamicArray[i].title2" class="form-control">
<option *ngFor="let data of dynamicArray[i].dropdownDataDesktop;">{{data?.name ? data?.name : data}}</option>
</select>
<!-- show account data -->
<input *ngIf="dynamicArray[i].title1 == 3 && dynamic?.isText" type="text" [(ngModel)]="dynamicArray[i].title2" class="form-control">
</td>
</tr>
<tr>
<td (click)="addRow(0)">
<i class="fa fa-plus fa-2x"></i>
</td>
</tr>
</tbody>
</table>
</div>

forming an array from dynamic input fileds using angularjs

I am working on a employee attendance system where i need to know their attendance status.I am generating a dynamic form which contains a text input field and a checkbox for each employee using angularjs ng-repeat inside a table to know whether the the employee was present or absent along with comments.I want to save the values of these dynamic text filed and checkbox using a single save button.Text fields may have null values or any other values and checkbox may be all checked,all unchecked and few checked and few unchecked. If the check box is checked then i want to save "checked":"yes" otherwise as no.I have also a single date input field to save the record for this particular date.
I think the solution of my situation is forming a dynamic array from inputs and assign it to a variable but and don't know how to form array dynamically in angularjs and then pass the array to a php page.Can you help me on this issue?
My expected array format is :
[{"Did":"10","supervisor":"ms1001","date":"2017-06-01",
"info":
{"eid":"10","checked":"yes","cmnt":"on time"},
{"eid":"20","checked":"NO", "cmnt":"absent"},
{"eid":"30","checked":"yes","cmnt":""},
{"eid":"40","checked":"NO","cmnt":"OK"},
{"eid":"50","checked":"YES","cmnt":""},
{"eid":"60","checked":"YES","cmnt":""},
{"eid":"70","checked":"YES","cmnt":""},
{"eid":"80","checked":"NO","cmnt":"Late"},
{"eid":"90","checked":"YES","cmnt":""}
}];
I will store the input details in attendance table which schema is
attendance(did,eid,date,checked,comment,supervisor_id)
var myApp = angular.module('myApp',['ui.bootstrap']);
myApp.controller('MyCtrl', function($scope) {
$scope.list = [
{"dept_id":"d10","dname":"sales","supervisor":"ms1001"},
{"eid":"10","ename":"nam1"},
{"eid":"20","ename":"nam2"},
{"eid":"30","ename":"nam3"},
{"eid":"40","ename":"nam4"},
{"eid":"50","ename":"nam5"},
{"eid":"60","ename":"nam6"},
{"eid":"70","ename":"nam7"},
{"eid":"80","ename":"nam8"},
{"eid":"90","ename":"nam9"},
{"eid":"120","ename":"nam10"}
];
$scope.did= $scope.list[0].dept_id;
$scope.dname= $scope.list[0].dname;
$scope.sp_name= $scope.list[0].supervisor;
$scope.selectedText = 'Select All';
$scope.isAll = false;
$scope.selectAll = function() {
if($scope.isAll === false) {
angular.forEach($scope.list, function(data){
data.checked = true;
});
$scope.isAll = true;
$scope.selectedText = 'Deselect All';
} else {
angular.forEach($scope.list, function(data){
data.checked = false;
});
$scope.isAll = false;
$scope.selectedText = 'Select All';
}
};
$scope.selectedFriends = function () {
return $filter('filter')($scope.list, {checked: true });
};
//date picker
$scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.dateOptions = {
formatYear: 'yy',
startingDay: 1
};
$scope.format = 'dd-MMMM-yyyy';
//end of date picker
});
<html>
<head>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.angularjs.org/1.6.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"></script>
<script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<style>
.full button span {
background-color: limegreen;
border-radius: 32px;
color: black;
}
.partially button span {
background-color: orange;
border-radius: 32px;
color: black;
}
</style>
</head>
<div class="container">
<div ng-app="myApp" ng-controller="MyCtrl">
<div class="row">
<div class="col-sm-3" style="background-color:yellow;">
<p>Department ID::{{did}}</p>
</div>
<div class="col-sm-3" style="background-color:skyblue;">
<p>Dept Name:{{dname}}</p>
</div>
<div class="col-sm-3" style="background-color:pink;">
<p>Supervisor name name:{{sp_name}}</p>
</div>
<div class="col-sm-3">
<p class="input-group">
<input type="text" class="form-control" uib-datepicker-popup="{{format}}"
ng-model="list.dt" is-open="opened" min-date="minDate" max-date="'2018-06-22'"
ng-model-options="{timezone: 'UTC'}"
datepicker-options="dateOptions" date-disabled="disabled(date, mode)"
ng-required="true" close-text="Close" />
<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>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Employee ID</th>
<th>name</th>
<th><label>Attendence</label><br><span id="selectall" ng-click="selectAll()"><input
type="checkbox">{{selectedText}}</span></th>
<th>comment</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="data in list" ng-if="$index">
<td> {{ data.eid }} </td>
<td> {{ data.ename }} </td>
<td> <input type="checkbox" value="{{ data.eid}}" ng-checked="data.checked" ng-model="data.checked"></td>
<td>
<input type="text" ng-model="data.cmnt" ></td>
</tr>
</tbody>
</table>
<pre>{{list}}</pre>
</div>
<button type="button" ng-click="saveAll()">Save all</button>
</div>
</html>
HTML
<table border="1">
<tr>
<td>Employee ID</td>
<td>Name</td>
<td>Attendance</td>
</tr>
<tr ng-repeat="employee in employees">
<td>{{employee.eid}}</td>
<td>{{employee.ename}}</td>
<td><input type="checkbox" name="check" ng-model="employee.att">
</td>
</tr>
</table>
<button ng-click="saveForm()">Save all</button>
<pre>{{employees}}</pre>
JS
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http) {
//initial data to display on table.
$scope.employees = [
{eid:"10",ename:"nam1", att: false},
{eid:"20",ename:"nam2", att: false},
{eid:"30",ename:"nam3", att: false},
];
//on save
$scope.saveForm = function (){
$http({
method: 'POST',
url: '/ana/testone',
data: $.param({formData: angular.copy($scope.employees)}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response) {
console.log(response);
});
}
});
PHP
$data = $_POST['formData'];
echo json_encode($data);

How to avoid flickering effect in angularjs

Can anybody help me how to fix this flicker effect when view is loading here is my code.
app.config(function($stateProvider,$urlRouterProvider,$routeProvider, $locationProvider,blockUIConfig) {
$urlRouterProvider.otherwise("/#");
$stateProvider
.state('dash', {
url: "/dash",
templateUrl: 'views/br_manager/pc_dashboard.html',
controller:'dashCtrl'
})
.state('pass', {
url: "/pass",
templateUrl: 'views/br_manager/change_password.html',
controller:'passwordCtrl'
})
.state('classroom', {
abstract:true,
url: "/classroom",
template: '<div ui-view style="height:100%"></div>',
controller:'classroomManagementCtrl'
})
.state('classroom.list', {
url: "",
templateUrl: 'views/br_manager/CR.html'
})
$locationProvider.html5Mode(true);
blockUIConfig.message = "Processing ...";
});
following is the code for controller and factory sevrvice
branchManager.factory('classroomFactory',function($resource,appConfig,$window){
var factory = {};
var fetch_classroom_url = appConfig.getMainAPI();
var authCode = $window.localStorage.getItem("authCode");
factory.fetchStandardList = function(selectedYear) {
return $resource(fetch_classroom_url+'/classroom/year/'+ selectedYear, {}, {
fetch : {
method : 'get',
isArray : false,
headers : { 'Authorization' : authCode },
interceptor : {
response : function(data) {
return data;
}
}
}
});
};
factory.fetchSectionList = function(currentStandard, selectedYear) {
return $resource(fetch_classroom_url+'/classroom/standard/'+ currentStandard +'/section/year/'
+ selectedYear, {}, {
fetch : {
method : 'get',
isArray : false,
headers : { 'Authorization' : authCode },
interceptor : {
response : function(data) {
return data;
}
}
}
});
};
return factory;
});
branchManager.controller('classroomManagementCtrl', function($scope,classroomFactory,appConfig,$state,$modal) {
var initials = {
syllabus:"",section:"",standard:"",year:"",classRoomId:"",maxcount:"",maxCount:""
};
$scope.year_list = ["2015-16","2016-17","2017-18","2018-19"];
$scope.fetchYearList = function(){
$scope.selectedYear = $scope.year_list[0];
$scope.fetchStandardList($scope.selectedYear);
};
$scope.fetchStandardList = function(selectedYear){
var year = window.btoa(selectedYear);
classroomFactory.fetchStandardList(year).fetch({},function(response){
$scope.standard_list =[];
if(response.status == 200 || response.status == 201){
if(response.data.standards != undefined){
var _data = angular.fromJson(response.data.standards);
$scope.standard_list = _data;
console.log( $scope.standard_list);
if($scope.standard_list.length > 0){
$scope.currentStandard = $scope.standard_list[0];
$scope.fetchSectionList($scope.currentStandard,selectedYear);
}else{
$scope.standard_list = ["-Nil-"];
}
}
}
},function(response){
$scope.standard_list = [];
$scope.currentStandard = "-Nil-";
$scope.response_msg = "There is no Standards found for this year.";
$scope.fetchSectionList($scope.currentStandard,selectedYear);
console.log(response.status);
});
};
$scope.fetchSectionList = function(currentStandard,selectedYear){
$scope.response_msg = "";
var standart = window.btoa(currentStandard);
var year = window.btoa(selectedYear);
classroomFactory.fetchSectionList(standart,year).fetch({},function(response){
$scope.classroom_list =[];
console.log(response);
if(response.status == 200 || response.status == 201){
if(response.data.classRoomLists!=undefined){
var _data = angular.fromJson(response.data.classRoomLists);
$scope.classroom_list = _data;
console.log( $scope.classroom_list);
$scope.$parent.setBaseContentHeight($scope.classroom_list.length);
}
}
},function(response){
$scope.classroom_list = [];
$scope.response_msg = "There is no classrooms found for this standard.";
$scope.$parent.setBaseContentHeight(-1);
console.log(response.status);
});
};
$scope.init = function(){
$scope.fetchYearList();
console.log("Init called")
};
$scope.cancel = function () {
$scope.response_msg = "";
$scope.response_msg1 = "";
$state.go('^.list');
};
$scope.init();
});
and my view looks like
<div class="col-lg-8 base-content table-base" style="height:90%;">
<div class="container-fluid" style="height: 90%;padding:0">
<div class="container-fluid" style="height: 30px;padding:0">
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-4" style="font-size: medium;padding: 0 0 10px 0px" >
<a ui-sref="^.add"><button type="button" ng-click="addClassroom()" class="btn btn-color btn-sm">Add ClassRooms</button></a>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3" style="padding: 0 0 20px 20px">
<select class="input-sm form-control" ng-model="selectedYear"ng-change="fetchStandardList(selectedYear)" ng-options="year as year for year in year_list" style="line-height: 1.5">
<option value="" selected="selected">-Year-</option>
</select>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3" style="padding: 0 0 20px 20px">
<select class="input-sm form-control" ng-model="currentStandard" ng-change="fetchSectionList(currentStandard,selectedYear)" ng-options="currentStandard as currentStandard for currentStandard in standard_list" style="line-height: 1.5">
<option value="" selected="selected">-Class-</option>
</select>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 text-success response_msg" style="padding-top: 10px;" ng-hide="response_msg == undefined || response_msg == ''" >{{response_msg}}</div>
</div>
<div class="container-fluid" style="height:auto;padding:0;" ng-if="classroom_list== undefined || classroom_list.length <= 10">
<table class="table table-striped">
<thead>
<tr>
<th width="10%">Classroom Id</th>
<th width="10%">Year</th>
<th width="10%">Standard</th>
<th width="10%">Section</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="classroom in classroom_list">
<td width="10%">{{classroom.classRoomId}}</td>
<td width="10%">{{classroom.year}}</td>
<td width="10%">{{classroom.standard}}</td>
<td width="10%">{{classroom.section}}</td>
</tr>
</tbody>
</table>
<div ng-if="classroom_list.length == 0 || standard_list.length == 0" class="noData">No Classrooms Found</div>
<!-- <div ng-if="classroom_list == undefined " class="noData">Processing...</div>-->
</div>
<div class="container-fluid" style="padding:0" ng-if="classroom_list != undefined && classroom_list.length > 10">
<table class="table">
<thead>
<tr>
<tr>
<th width="10%">Classroom Id</th>
<th width="10%">Year</th>
<th width="10%">Standard</th>
<th width="10%">Section</th>
</tr>
</thead>
</table>
</div>
<div class="container-fluid slim-content" style="padding:0;" ng-if="classroom_list != undefined && classroom_list.length > 10" slim-scroll="{height:'88%',size:'3px',allowPageScroll :true,width:'100%'}">
<table class="table table-striped">
<tbody>
<tr ng-repeat="classroom in classroom_list">
<td width="10%">{{classroom.classRoomId}}</td>
<td width="10%">{{classroom.year}}</td>
<td width="10%">{{classroom.standard}}</td>
<td width="10%">{{classroom.section}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
any answers will be helpful thanks in advance.

Not able to push $log data to txt file

I have a local amp setup where I am trying to push angular $log messages to a txt file. But I keep getting a javaScript error. Here is the error
angular.js:9101 TypeError: $scope.todos.push is not a function
Here is my code:
angular.module('Todo', []).factory('myhttpserv', function($http) {
return $http.get('storage.txt').error(function(status) {
console.log(status)
});
}).controller('TodoController', function($scope, myhttpserv, $http) {
$scope.appTitle = "MyTodoList",
myhttpserv.then(function(response) {
$scope.todos = (response.data !== null) ? response.data : [];
var httpPost = function() {
$http.post('save.php', JSON.stringify($scope.todos)).error(function(status) {
console.log(status)
});
};
$scope.addTodo = function() {
$scope.todos.push({
text: $scope.todoText,
doneProd: false,
doneDev: false
});
$scope.todoText = ''; //clear the input after adding
httpPost();
};
$scope.remaining = function() {
var count = 0;
angular.forEach($scope.todos, function(todo) {
count += todo.doneProd && todo.doneDev ? 0 : 1;
});
return count;
};
$scope.archive = function() {
var rusure = confirm("Are you sure you want to remove the completed tasks from the list?");
if (rusure) {
var oldTodos = $scope.todos;
$scope.todos = [];
angular.forEach(oldTodos, function(todo) {
if (!todo.doneProd || !todo.doneDev)
$scope.todos.push(todo);
});
httpPost();
}
};
$scope.delete = function(idx) {
var rusure = confirm("Are you sure you want to remove the task from the list?");
if (rusure) {
$scope.todos.splice(idx, 1);
httpPost();
}
};
$scope.edit = function(idx) {
var changes = prompt("Please make the changes below", $scope.todos[idx].text);
if (changes != null) {
$scope.todos[idx].text = changes;
httpPost();
}
};
$scope.checkboxClick = function() {
httpPost();
};
$('.splash, .container').fadeToggle();
});
});
<div class="splash">
<h2>Loading</h2>
</div>
<div class="container">
<header class="app-header">
<h1 class="app-title" data-ng-bind="appTitle"></h1>
</header>
<section class="app-body">
<table>
<thead>
<tr>
<th>
TITLE
</th>
<th></th>
<th></th>
<th class="chk">
PROD
</th>
<th class="chk">
DEV
</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="todo in todos track by $index">
<td>
<span class="done-{{ todo.doneProd && todo.doneDev }}" data-ng-bind="todo.text"></span>
</td>
<td>
<a data-ng-click="delete($index)"><i class="fa fa-times"></i></a>
</td>
<td>
<a data-ng-click="edit($index)"><i class="fa fa-pencil-square-o"></i></a>
</td>
<td class="chk">
<input type="checkbox" data-ng-model="todo.doneProd" data-ng-change="checkboxClick()">
</td>
<td class="chk">
<input type="checkbox" data-ng-model="todo.doneDev" data-ng-change="checkboxClick()">
</td>
</tr>
</tbody>
</table>
<section class="archive-control">
<span>{{ remaining() }} of {{ todos.length }} remaining</span>
<a class="fr" href="" data-ng-click="archive()" data-ng-show="remaining() < todos.length">Remove Completed Items</a>
</section>
<form data-ng-submit="addTodo()" class="todo-form">
<input type="text" data-ng-model="todoText" placeholder="Enter new task item" />
<br />
<input type="submit" value="Add Task" />
</form>
</section>
</div>
here is my php file and I do have my storage.txt in the folder also:
<?php
$data = file_get_contents("php://input");
$myfile = fopen("log.txt", "w") or die("Unable to open file!");
fwrite($myfile, $data);
fclose($myfile);
?>

How to append json values to html[value]

I have Json like this. How to append the json values into html input values.
[{"user_id":"180",
"firstname":"anandhsp",
"lastname":"sp",
"email":"xyz#gmail.com",
"mobile":"9000000000",
"gender":null,
"hashcode":"2XXg3dfyuxjO9C4OvaWw",
"username":"anandhsp21",
"password":"64c20f8bb630eb5cb329fdd609c807b7:J6",
"emailverify":"TRUE",
"company_name":"xxx",
"address":"Chennai",
"city":"Chennai",
"state":"Tamilnadu",
"pincode":"637001",
"phone":"1234567890",
"website":"hello",
"nature":"hello",
"no_employe":"23",
"year":"2015",
"type":"Proprietor",
"authorized_person":"Anandh Sp",
"status":"",
"created":"2015-06-26 10:48:09",
"modified":"2015-06-11 11:24:39",
"logdate":"2015-06-26 05:18:09",
"lognum":"3",
"reload_acl_flag":"0",
"is_active":"1",
"extra":"N;",
"rp_token":null,
"rp_token_created_at":null,
"app_name":"",
"api_key":""}]
Html code
<div id="register_form" class="fieldset subgroupregister_form">
<div class="hor-scroll">
<table class="form-list" cellspacing="0">
<tbody>
<tr class="tr_tag">
<tr class="tr_application_id">
<tr class="tr_customer_id">
<tr class="tr_company_name">
<tr class="tr_address">
<td class="label">
<td class="value">
<input id="address" class=" input-text required-entry" type="text" value="" name="address">
</td>
</tr>
<tr class="tr_city">
<tr class="tr_state">
<tr class="tr_pincode">
<tr class="tr_mobile">
<tr class="tr_phone">
<tr class="tr_website">
<tr class="tr_nature">
<tr class="tr_no_employe">
<tr class="tr_year">
<tr class="tr_type">
<tr class="tr_authorized_person">
<tr class="tr_status">
</tbody>
</table>
</div>
</div>
</div>
I need to append the above values into input value
For example
<input id="address" class=" input-text required-entry" type="text" value="chennai" name="address">
I tried these Codes.But I did't got output.
jQuery('.ac_results ul li').bind('click',function(e)
{
var text = $(this).text();
jQuery.ajax({
type: 'get',
url: BASE_URL + 'admin/index/user_id',
data: {email: text},
dataType:'json',
success: function (data) {
var data = data[0];
$('#address').value = data.address;
$('#city').value = data.city;
$('#state').value = data.state;
$('#pincode').value = data.pincode;
$('#mobile').value = data.mobile;
$('#phone').value = data.phone;
$('#website').value = data.website;
$('#email').value = data.email;
$('#nature').value = data.nature;
$('#year').value = data.year;
$('#no_employe').value = data.no_employe;
$('#type').value = data.type;
$('#authorized_person').value = data.authorized_person;
}
});
});
Thanks In advance
Try val() function:
$('input').val(obj.item);
Check the following example
var obj = { test: 'test' }
$('#add').on('click', function() {
$('#inp').val(obj.test);
});
$('#res').on('click', function() {
alert($('#inp').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="inp" type="hidden" />
<button id="add">Add value</button>
<button id="res">Show input</button>

Categories