Why my Angular js code is not working? - javascript

It is my code for angular js and html.Please help me about this.why it is not working with file if any error in syntax in html file or angular file?
I am trying to make a order table and I am doing it using angular js method and every time when I runs it on browser the Angular code is not working and Add button is also not working for me which is used to add the more entities in order.
angular.module('Commande', [])
.controller('commandeController', ['$scope', function($scope) {
$scope.articles = [
{ id: 1, reference: 123, titre: "MSI GTX 980ti", prixUnitaire: 666.63, quantite: 0, montantHT: 666.63, montantTTC: 799.95 },
{ id: 2, reference: 456, titre: "Intel Core i7-4770K", prixUnitaire: 324.96, quantite: 0, montantHT: 324.96, montantTTC: 389.95 },
{ id: 3, reference: 789, titre: "ASUS MAXIMUS VII RANGER", prixUnitaire: 134.96, quantite: 0, montantHT: 134.96, montantTTC: 161.95 }
];
$scope.PrixTotalTTC = function() {
var resultTTC = 0;
angular.forEach($scope.articles, function (article) {
resultTTC += article.montantTTC * article.quantite;
});
return resultTTC;
};
$scope.PrixTotalHT = function() {
var resultHT = 0;
angular.forEach($scope.articles, function (article) {
resultHT += article.montantHT * article.quantite;
});
return resultHT;
};
$scope.NombreArticle = function() {
var resultArticle = 0;
angular.forEach($scope.articles, function(article){
resultArticle += article.quantite;
});
return resultArticle;
};
$scope.AjouterArticle = function() {
$scope.articles.push({
id: '',
reference: '',
titre: '',
prixUnitaire: 0,
quantite: 0,
montantHT: 0,
montantTTC: 0
});
};
$scope.SupprimerArticle = function(index) {
$scope.articles.splice(index, 1);
};
}]);
<html lang="en-us">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<script src="//code.angularjs.org/1.6.6/angular.min.js">
</script>
<script src="app.js"></script>
</head>
<body ng-app="Commande" ng-controller="commandeController">
<h1>Bon de commande</h1>
<div class="content">
<div class="col-md-12">
<table class="table table-striped table-hover table-responsive">
<thead>
<tr>
<th>#</th>
<th>Référence</th>
<th>Titre</th>
<th>Prix unitaire HT/€</th>
<th>Quantité</th>
<th>Montant HT/€</th>
<th>Montant TTC/€</th>
<th>Supprimer</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="article in articles">
<th>
<input type="number" ng-model="article.id" class="form-control bfh-number" placeholder="Id" min=0>
</th>
<td>
<input type="number" ng-model="article.reference" class="form-control bfh-number" placeholder="Référence" min=0>
</td>
<td>
<input type="text" ng-model="article.titre" class="form-control" placeholder="Titre">
</td>
<td>
<input type="number" ng-model="article.prixUnitaire" class="form-control bfh-number">
</td>
<td>
<input type="number" ng-model="article.quantite" class="form-control bfh-number" min=0>
</td>
<td>
<input type="number" ng-model="article.montantHT" class="form-control bfh-number" min=0>
</td>
<td>
<input type="number" ng-model="article.montantTTC" class="form-control bfh-number" min=0>
</td>
<td>
<a href ng:click="SupprimerArticle($index)"><i class="fa fa-times delete"></i></a>
</td>
</tr>
<tr class="success">
<th class="success">TOTAL</th>
<td class="success"></td>
<td class="success"></td>
<td class="success"></td>
<td class="success">{{ NombreArticle() }} article(s)</td>
<td class="success" ng-style="PrixTotalHT() >= 1000 && {'font-weight': 'bold'}">{{ PrixTotalHT() | number:2 }} €</td>
<td class="success" ng-style="PrixTotalHT() >= 1000 && {'font-weight': 'bold'}">{{ PrixTotalTTC() | number:2 }} €</td>
<td class="success"></td>
</tr>
</tbody>
</table>
<a href ng:click="AjouterArticle()" class="btn btn-primary">Ajouter un article <i class="fa fa-plus"></i></a>
</div>
</div>
</body>
</html>
It is my code.

Sounds like you need a content management system (CMS), such as MAMP, XAMPP or similar. You basically need to run a local server for JavaScript code to work (as well as any PHP you might use). Simple solution, if just need JavaScript, is to use Node.js.

Related

division work and sum in jquery not work?

i have a datatable with checkbox and a button add, i want when i click on button add, console display salaire and prime and sold which calculate like that sold = (salaire / 24) + prime.
index.php
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div id="form2">
<table class="table table-bordered" id="mytable">
<tr>
<th><input type="checkbox" id="check_all"></th>
<th>nom</th>
<th>salaire</th>
<th>adresse</th>
<th>prime</th>
</tr>
<tr>
<td><input type="checkbox" class="checkbox"></td>
<td>najib</td>
<td>5000</td>
<td>tihit</td>
<td><input type="text" name="prime" class="form-control prime" value="0"></td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox"></td>
<td>adil</td>
<td>4000</td>
<td>tagmast</td>
<td><input type="text" name="prime" class="form-control prime" value="0"></td>
</tr>
</table>
<div class="form-group col-md-offset-5 ">
<button class="btn btn-success " type="submit" id="add">Pointage men</button>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function(){
var items = [];
$("tr").each(function(i,r){
let salaire = r.cells[2].innerText;
let prime = $(r).find(".prime").val();
let sold = ((salaire)/24) + prime;
if ( i > 0 && $(r).find("input").first().prop("checked")){
items.push({ "salaire" : salaire , "prime" : prime , "sold" : sold });
}
})
console.log(items);
})
})
</script>
This happens since variables salaire and prime are actually returned in code as string and thus when you do this:
console.log( ('5000'/24) + '100' )
then answer is also returned as a string like "208.33333333333334100"
So, you just need to convert them to integer first and it should work fine like:
let salaire = '5000'
let prime = '100'
let sold = ((+salaire) / 24) + +prime;
console.log(sold)

jquery DataTables parent and child rows posted to server as one record instead of two

I have a problem where jquery DataTables creates parent and child rows on resize (responsive DataTable) and I need to save values of inputs from child rows as well as from parent rows and post via ajax to controller action.
Responsive (resized) DataTable:
Normal (not resized) DataTable:
Currently I am using this jquery function to post data to the server:
$('#SaveItemButton').click(function (e) {
var arr = [];
var rows = $('#ItemTable').find('tbody').find('tr');
console.log(rows.length);
$.each(rows, function (index, item) {
var controls = $(this).find('input, select');
console.log(controls.length);
item = {
ItemType: controls.eq(0).val(),
Unit: controls.eq(1).val(),
Quantity: controls.eq(2).val(),
Price: controls.eq(3).val(),
InvoiceDate: $('#InvoiceDate').val(),
TransferDate: $('#TransferDate').val(),
TransferPlace: $('#TransferPlace').val(),
InvoiceDescription: $('#InvoiceDescription').val()
};
arr.push(item);
});
$.ajax({
url: '/Item/Add',
data: JSON.stringify(arr),
contentType: 'application/json',
type: "POST",
dataType: "json",
success: function (result) {
//alert(result);
},
error: function (errormessage) {
}
});
return false;
});
but when the Datatable is resized it returns two rows which in turn gets posted to the server.
I am retrieving rows from a table via:
var rows = $('#ItemTable').find('tbody').find('tr');
How can I get all the related parent rows and child rows as one row so I can post that row to the server?
Parent row example:
<tr role="row" class="odd parent">
<td tabindex="0" style=""></td>
<td class="sorting_1"><input name="ItemType" class="form-control" type="text"></td>
<td style="display: none;"><select name="Unit" class="form-control defaultpicker"><option>dan</option><option>Komad</option><option>Sat</option>m<option>m2</option><option>m3</option><option>kg</option><option>lit</option><option>pak</option><option>reč</option></select></td>
<td style="display: none;"><input name="Quantity" class="form-control" type="number"></td>
<td style="display: none;"><input name="Price" class="form-control" type="text"></td>
<td style="display: none;"><input name="Total" class="form-control" type="text" readonly=""></td>
<td style="display: none;"><button type="submit" id="DeleteButton" class="fa fa-times select-row btn btn-secondary btn-sm" data-id=""></button>
</td>
</tr>
Child row example:
<tr class="child">
<td class="child" colspan="2">
<ul data-dtr-index="0" class="dtr-details">
<li data-dtr-index="2" data-dt-row="0" data-dt-column="2">
<span class="dtr-title">Unit</span>
<span class="dtr-data">
<select name="Unit" class="form-control defaultpicker"><option>dan</option><option>Komad</option><option>Sat</option>m<option>m2</option><option>m3</option><option>kg</option><option>lit</option><option>pak</option><option>reč</option></select>
</span>
</li>
<li data-dtr-index="3" data-dt-row="0" data-dt-column="3">
<span class="dtr-title">Quantity</span>
<span class="dtr-data">
<input name="Quantity" class="form-control" type="number" value="3">
</span>
</li>
<li data-dtr-index="4" data-dt-row="0" data-dt-column="4">
<span class="dtr-title">Price</span>
<span class="dtr-data">
<input name="Price" class="form-control" type="text" value="1000">
</span>
</li>
<li data-dtr-index="5" data-dt-row="0" data-dt-column="5">
<span class="dtr-title">Total</span>
<span class="dtr-data">
<input name="Total" class="form-control" type="text" readonly="" value="">
</span>
</li>
<li data-dtr-index="6" data-dt-row="0" data-dt-column="6">
<span class="dtr-title"></span>
<span class="dtr-data">
<button type="submit" id="DeleteButton" class="fa fa-times select-row btn btn-secondary btn-sm" data-id=""></button>
</span>
</li>
</ul>
</td>
</tr>
Controller posted data, index 0 contains valid data:
Code Snippet:
var table = $('#ItemTable').DataTable({
"dom": '<"toolbar">frtip',
"paging": true,
"pagingType": "full_numbers",
"searching": false,
// Solution to responsive table losing data
'columnDefs': [{
'targets': [1, 2, 3, 4, 5, 6],
'render': function(data, type, row, meta) {
if (type === 'display') {
var api = new $.fn.dataTable.Api(meta.settings);
var $el = $('input, select, textarea', api.cell({
row: meta.row,
column: meta.col
}).node());
var $html = $(data).wrap('<div/>').parent();
if ($el.prop('tagName') === 'INPUT') {
$('input', $html).attr('value', $el.val());
if ($el.prop('checked')) {
$('input', $html).attr('checked', 'checked');
}
} else if ($el.prop('tagName') === 'TEXTAREA') {
$('textarea', $html).html($el.val());
} else if ($el.prop('tagName') === 'SELECT') {
$('option:selected', $html).removeAttr('selected');
$('option', $html).filter(function() {
return ($(this).attr('value') === $el.val());
}).attr('selected', 'selected');
}
data = $html.html();
}
return data;
}
}],
'responsive': true,
order: [1, 'asc']
});
// Solution to responsive table losing data
$('#ItemTable tbody').on('keyup change', '.child input, .child select, .child textarea', function(e) {
var $el = $(this);
var rowIdx = $el.closest('ul').data('dtr-index');
var colIdx = $el.closest('li').data('dtr-index');
var cell = table.cell({
row: rowIdx,
column: colIdx
}).node();
$('input, select, textarea', cell).val($el.val());
if ($el.is(':checked')) {
$('input', cell).prop('checked', true);
} else {
$('input', cell).removeProp('checked');
}
});
$('#SaveItemButton').click(function() {
var arr = [];
var rows = $('#ItemTable').find('tbody').find('tr');
console.log(rows.length);
$.each(rows, function(index, item) {
var controls = $(this).find('input, select');
console.log(controls.length);
item = {
ItemType: controls.eq(0).val(),
Unit: controls.eq(1).val(),
Quantity: controls.eq(2).val(),
Price: controls.eq(3).val(),
InvoiceDate: $('#InvoiceDate').val(),
TransferDate: $('#TransferDate').val(),
TransferPlace: $('#TransferPlace').val(),
InvoiceDescription: $('#InvoiceDescription').val()
};
arr.push(item);
});
$.ajax({
url: '/Item/Add',
data: JSON.stringify(arr),
contentType: 'application/json',
type: "POST",
dataType: "json",
success: function(result) {
//alert(result);
},
error: function(errormessage) {
}
});
return false;
});
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/responsive/2.2.3/css/responsive.dataTables.min.css" rel="stylesheet" />
<table id="ItemTable" class="table table-hover table-secondary dataTable no-footer dtr-inline" style="width: 100%;" role="grid" aria-describedby="ItemTable_info">
<thead>
<tr role="row">
<th></th>
<th>ItemType</th>
<th>Unit</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
<th></th>
</tr>
</thead>
<tbody>
<tr role="row" class="odd parent">
<td tabindex="0" style=""></td>
<td class="sorting_1"><input name="ItemType" class="form-control" type="text"></td>
<td style="">
<select name="Unit" class="form-control defaultpicker">
<option>value1</option>
<option>value2</option>
<option>value3</option>
<option>value4</option>
<option>value5</option>
<option>value6</option>
<option>value7</option>
<option>value8</option>
<option>value9</option>
</select>
</td>
<td style=""><input name="Quantity" class="form-control" type="number"></td>
<td style=""><input name="Price" class="form-control" type="text"></td>
<td style=""><input name="Total" class="form-control" type="text" readonly=""></td>
<td style=""><button type="submit" id="DeleteButton" data-id=""></button></td>
</tr>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/select/1.2.6/js/dataTables.select.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.3/js/dataTables.responsive.min.js"></script>
Well, you really cannot. At first DT inject and remove child rows and their content to and from the DOM, making them invisible to simple jQuery selectors. You can target open child rows, but that is all.
Secondly you cannot select multiple elements in pairs. You could have for example $('tr.parent, tr.parent ~ tr.child') or similar, but that would be equal to just $('tr'). I would go through the API:
table.rows().every(function() {
var $node = this.nodes().to$();
var item = {
ItemType: $node.find('input[name=ItemType]').val(),
Unit: $node.find('select[name=Unit]').val(),
Quantity: $node.find('input[name=Quantity]').val(),
Price: $node.find('input[name=Price]').val(),
Total: $node.find('input[name=Total]').val(),
InvoiceDate: $('#InvoiceDate').val(),
TransferDate: $('#TransferDate').val(),
TransferPlace: $('#TransferPlace').val(),
InvoiceDescription: $('#InvoiceDescription').val()
};
arr.push(item)
})
Completely untested. See JQuery Datatables search within input and select on how to update the DT internals when form controls is changing. Otherwise you will just get return default / original values.

Blink cell on data change AngularJS

so I'm new to Angular and JS and I've been trying to do something simple with no success.
I have a table with data, everytime this data gets changed I want to make a fade in fade out animation so it blinks. I assumed I could use $watch to watch if an element changes but it's not working.
This is what I got so far:
HTML:
<tbody md-body>
<tr md-row ng-repeat="item in info.data">
<td md-cell>{{item.name}}</td>
<td md-cell>{{item.id}}</td>
<td md-cell>{{item.thing2}}</td>
<td md-cell>{{item.thing3}}</td>
<td md-cell>{{item.thing4}}</td>
<td md-cell>{{item.thing5}}</td>
</tr>
</tbody>
JS:
$scope.info = {
"data": [
{
name: "ELI 0001",
id: "123",
thing1: "thing",
thing2: "thing",
thing3: "thing",
thing4: "thing",
thing5:"thing",
},
{
name: "ELI 0001",
id: "123",
thing1: "thing",
thing2: "thing",
thing3: "thing",
thing4: "thing",
thing5:"thing",
},
]
};
I added this function to watch the entire data set for changes, and when it does I made an alert. I also added the var initialising so it doesn't show up as soon as it loads.
var initializing = true
$scope.$watch('if',function(){
if (initializing) {
$timeout(function() { initializing = false; });
} else {
alert('hey')
}
})
My problem is, how can I get it to watch all cells and execute a class that does the animation only on the data that changed?
AS this thread https://groups.google.com/forum/#!msg/angular/xZptsb-NYc4/rKAxJ3dQhbMJ, what I ended up doing was this:
app.directive('highlightOnChange', function() {
return {
link: function($scope, element, attrs) {
attrs.$observe('highlightOnChange', function(val) {
var el = $(element);
el.removeClass('blink_me ');
_.defer(function() {
el.addClass('blink_me ')
});
});
}
};
});
That is, creating a directive observes the property. You can then use it like this:
<td md-cell highlight-on-change="{{item.name}}"></td>
...
suppose your css class be:
.blink_me {
animation: blinker 1s linear infinite;
}
#keyframes blinker {
50% {
opacity: 0;
}
}
I was working on a similar approach to #khateeb -- except I am using a $watch on the element's ng-model instead of using $observe on the directive attribute. Both work!
Plunker: https://embed.plnkr.co/rZVjPmDft997Kmny1LS4/
Snippet:
(function() {
"use strict";
var app = angular
.module('plunker', [])
.controller('MainCtrl', MainCtrl)
.directive('flashTd', flashTD);
function flashTD($timeout, $compile) {
return {
scope: {
ngModel: '='
},
link: function($scope, elem, attrs) {
// Set a watch on ng-model to wait for value change
$scope.$watch('ngModel', function(newVal, oldVal) {
if (newVal !== oldVal) {
// Flash row
// var row = angular.element(elem[0].parentNode.parentNode);
// Flash td
var td = angular.element(elem[0].parentNode);
// Using a timeout to simulate remote data change
$timeout(function() {
if (td.hasClass('flash')) {
td.removeClass('flash');
}
$timeout(function() {
td.addClass('flash')
})
}, 2000)
}
})
}
}
}
MainCtrl.$inject = ["$scope"];
function MainCtrl($scope) {
// Sample Data
$scope.info = {
"data": [{
name: "ELI 0001",
id: "123",
thing1: "thing",
thing2: "thing",
thing3: "thing",
thing4: "thing",
thing5: "thing",
}, {
name: "ELI 0001",
id: "1234",
thing1: "thing",
thing2: "thing",
thing3: "thing",
thing4: "thing",
thing5: "thing",
}]
};
}
})()
.editPencil:hover {
cursor: pointer;
}
/* https://stackoverflow.com/questions/14607695/flashing-table-row */
#keyframes flash {
from {
background-color: #ffbe76;
}
to {
background-color: inherit;
}
}
.flash {
animation: flash 1s 1;
}
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS - Flash TD on Change</title>
<link data-require="bootstrap#3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="style.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script data-require="bootstrap#3.3.7" data-semver="3.3.7" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script data-require="angular.js#1.3.x" src="https://code.angularjs.org/1.3.20/angular.js" data-semver="1.3.20"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="jumbotron text-center">
<h3>AngularJS - Flash TD on Change</h3>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<form class="form">
<div class="form-group">
<table class="table">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Id</th>
<th>Thing1</th>
<th>Thing2</th>
<th>Thing3</th>
<th>Thing4</th>
<th>Thing5</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in info.data">
<td class="editPencil glyphicon-pencil text-center" style="transform: rotate(45deg)" ng-click="editRow = !editRow"></td>
<td>
<span ng-hide="editRow">{{ item.name }}</span>
<input type="text" class="input-sm" ng-model="item.name" ng-hide="!editRow" flash-td />
</td>
<td>
<span ng-hide="editRow">{{ item.id }}</span>
<input type="text" class="input-sm" ng-model="item.id" ng-hide="!editRow" flash-td />
</td>
<td>
<span ng-hide="editRow">{{ item.thing1 }}</span>
<input type="text" class="input-sm" ng-model="item.thing1" ng-hide="!editRow" flash-td />
</td>
<td>
<span ng-hide="editRow">{{ item.thing2 }}</span>
<input type="text" class="input-sm" ng-model="item.thing2" ng-hide="!editRow" flash-td />
</td>
<td>
<span ng-hide="editRow">{{ item.thing3 }}</span>
<input type="text" class="input-sm" ng-model="item.thing3" ng-hide="!editRow" flash-td />
</td>
<td>
<span ng-hide="editRow">{{ item.thing4 }}</span>
<input type="text" class="input-sm" ng-model="item.thing4" ng-hide="!editRow" flash-td />
</td>
<td>
<span ng-hide="editRow">{{ item.thing5 }}</span>
<input type="text" class="input-sm" ng-model="item.thing5" ng-hide="!editRow" flash-td />
</td>
</tr>
</tbody>
</table>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Directive
In my demo, I'm flashing the td, but you can as easily change it to flash the target's table row by using the commented-out row variable instead of the td variable.
app.directive('flashTd', flashTD);
function flashTD($timeout, $compile) {
return {
scope: {
ngModel: '='
},
link: function($scope, elem, attrs) {
// Set a watch on ng-model to wait for value change
$scope.$watch('ngModel', function(newVal, oldVal) {
if (newVal !== oldVal) {
// Flash row
// var row = angular.element(elem[0].parentNode.parentNode);
// Flash td
var td = angular.element(elem[0].parentNode);
// Using a timeout to simulate remote data change
$timeout(function() {
if(td.hasClass('flash')) {
td.removeClass('flash');
}
$timeout(function() {
td.addClass('flash')
})
}, 2000)
}
})
}
}
}
HTML Element
<input type="text" class="input-sm" ng-model="item.thing2" ng-hide="!editRow" flash-td />

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 modify and update data table row in angular js?

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

Categories