Angular js to angular 8 - javascript

I am writing an Angular application and I have an old code i want to convert this angular js code to angular
table.html
<table ng-repeat="group in vm.groups" style="float: left">
<thead>
<tr>
<th><b>Sl. No</b></th>
<th><b>Generated Code</b></th>
</tr>
</thead>
<tr ng-repeat="g in group.values">
<td ng-style="$odd ? {'background': 'lightgrey' } : {'background': 'white' }">{{$parent.$index * 10 + $index + 1}}</td>
<td ng-style="$odd ? {'background': 'lightgrey' } : {'background': 'white' }">{{g.value}}</td>
</tr>
</table>
table.ts
app.controller('Ctrl', function() {
var vm = this;
var items = [{value: 'bbb'},{value: 'bbb'},{value: 'bbb'},{value: 'bbb'},{value: 'bbb'}];
vm.groups = [];
var i,j,temparray,chunk = 10;
for (i=0,j=items.length; i<j; i+=chunk) {
temparray = items.slice(i,i+chunk);
vm.groups.push({values: temparray});
}
});
i Want to convert this code to Angular2+. I am new to angular please help me.

Angular 2 onwards you should use *ngFor directive to loop over array.
so , your component.html should look like below :
<table *ngFor="let group of groups; let i=index">
<thead>
<tr>
<th><b>Sl. No</b></th>
<th><b>Generated Code</b></th>
</tr>
</thead>
<tr *ngFor="let g of group.values; let x=index" [ngClass]="(x%2===0)?'even':'odd'">
<td>{{i * 10 + x + 1}}</td>
<td>{{g.value}}</td>
</tr>
</table>
Below is the Angular 8 conversion of your code : demo

Related

how to use angularJS with appended elements

Basically, i have a structure like this example
Every cell of last column needs to have this formula:
value[i][2] = value[i-1][2] + value[i][0] - value[i][1]
I'm actually having 2 problems. The first one comes when i just try to program the first row of the table. What's wrong with this extremely simple thing?
angular.module('calc', [])
.controller('cont', function($scope) {
$scope.addNumbers = function() {
var c = aCom[30][5];
var a = parseFloat($scope.entrata1);
var b = parseFloat($scope.uscita1);
return c+a-b;
}
});
considering entrata1 and uscita1 as they are value[0][0] and value[0][1].
But most important, how can I extend the formula to all other rows? Consider that every row except the first one is created dinamically with an appendChild()function to the body, do i have to use at every appended item the function setAttribute("ng-model","entrata")?
Thanks
I would suggest forget appendchild. Use ng-repeat and add rows adding to the scope
like this
angular.module('plunker', []).controller('tableCtrl', function($scope,$filter) {
$scope.rows = [{'a': 0,'u': 300},{'a': 0,'u': 150},{'a': 200,'u': 0},{'a': 0,'u': 300}];
$scope.rowscalc = function(val){
var total=0;
angular.forEach($scope.rows, function(values, key){
if(key<=val) total += values.u-values.a;});
return total;
};
$scope.addRowM = function(){
$scope.rows.push({'a': 0, 'u': 0});
};
});
<script src="//unpkg.com/angular/angular.js"></script>
<div ng-app="plunker" ng-controller="tableCtrl">
<table class="table">
<thead>
<tr>
<td class="dthead">A</td>
<td class="dthead">U</td>
<td class="dthead">Total</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in rows">
<td><input type="number" ng-model="row.a"/></td>
<td><input type="number" ng-model="row.u"/></td>
<td>{{rowscalc($index)}}</td>
</tr>
<tr>
<td colspan="3">
<button ng-click="addRowM()">Add Row</button>
</td>
</tr>
</tbody>
</table>
</div>
you can check in plunker

Function isn't called with responsed data

Hello I got a weird problem... I lost almost 2 hrs and I have no idea why it doesn't work.
It should sum all values for every dept where username = name choosed by select and where date = date choosed by datepicker.
It works great on jsFiddle but when I am trying use it with responsed data it doesn't work and don't have any errors in console.
What am I doing wrong? This is code in my app not the same which is in jsFiddle
HTML:
<div layout="row">
<md-datepicker ng-model="myDateUser" md-placeholder="Enter date"></md-datepicker>
{{myDateUser}}
<md-input-container flex="50">
<label for="repeatSelect"> Select user: </label>
<md-select ng-model="data.model" ng-change="sum(data.model)">
<md-option ng-value="logins.name" ng-repeat="logins in chooseLogins">{{logins.name}}</md-option>
</md-select>
</md-input-container>
<br/>
<hr/>
<tt>{{data.model}}</tt>
</div>
<md-table-container>
<table md-table>
<thead md-head>
<tr md-row>
<th md-column>Dept</th>
<th md-column>Total time</th>
<th md-column></th>
</tr>
</thead>
<tbody md-body>
<tr ng-if="!data.model" md-row md-select="test" md-on-select="" md-auto-select ng-repeat="test in tests">
<td md-cell>{{ test.dept }}</td>
<td md-cell>{{ test.total }}</td>
<td md-cell></td>
</tr>
<tr ng-if="data.model" md-row md-select="test" md-on-select="" md-auto-select ng-repeat="(key,val) in data.model">
<td md-cell>{{ key }}</td>
<td md-cell>{{ val }}</td>
<td md-cell></td>
</tr>
</tbody>
</table>
</md-table-container>
JS:
function getTotalTime() {
$http.get('db_files/totalTimeDB.php').then(function(response) {
$scope.data = response.data;
$scope.sum = function(name) {
let model = $scope.data.filter(function(item) {
return (item.username == name && TheDate(item))
});
let tests = {};
model.forEach(function(item) {
if (!tests.hasOwnProperty(item.dept)) {
tests[item.dept] = 0;
}
tests[item.dept] += parseFloat(item.task_time);
});
$scope.data.model = tests;
}
function TheDate(item){
if($scope.myDateUser){
var myDateUser = new Date($scope.myDateUser);
var itemDate = new Date(item.task_end);
console.log("task_end " + item.task_end);
console.log("myDate " + $scope.myDateUser);
if(myDateUser.getFullYear() != itemDate.getFullYear() || myDateUser.getMonth() != itemDate.getMonth()){
return false;
}
}
return true
}
Example console.log from $scope.data = response.data;
Object
dept:"Test2"
status:"Closed"
task:"test test test"
task_end:"2016-09-02"
task_start:"2016-09-02"
task_time:"80"
username:"Nelson"
__proto__:Object
It works like show total sum only where username = choosed name and TheDate function is ignored. Also console.log shows nothing ( in example jsFiddle console.log shows selected date and name )
It looks like the function isn't called.

How do I get the total sum in ng-init and ng-repeat - angularjs

Having a problem with in ng-init and ng-repeat angularjs
i'm trying to loop the fields rates to get the total
for example this is my table
nane +++++++id+++++++rate
joe +++++++++1+++++++3
joe +++++++++2+++++++3
joe +++++++++3+++++++3
joe +++++++++4+++++++3
this my code.
<table>
<tr>
<td>name</td>
<td>rate</td>
</tr>
<tr ng-repeat="item in videos">
<td>{{item.name}}</td>
<td ng-init="videos.total.rate = videos.total.rate + item.rate">{{item.rate}}</td>
</tr>
<tr>
<td>Total</td>
<td>{{videos.total.rate}}</td>
</tr>
The Result that I get is 3333 instead of 12 when added all together
this is the line with problem
<td ng-init="videos.total.rate = videos.total.rate + item.rate">{{item.rate}}</td>
if i change it to a number it works fine.
<td ng-init="videos.total.rate = videos.total.rate + 3">{{item.rate}}</td>
your help would be great.thanks
Try something like this in controller.
JS
$scope.RateTotal= 0;
for (var i = 0; i < data.length; i++) {
$scope.RateTotal= $scope.RateTotal + data[i].rate;
}
HTML
<p>{{RateTotal}}</p>
Option above is better, but if you want use ng-init use something like this.
<table ng-init="RateTotal = 0">
<thead>
<th>Rate</th>
</thead>
<tbody>
<tr ng-repeat="item in videos">
<td ng-init="$parent.RateTotal= $parent.RateTotal + item.rate">{{item.rate}}</td>
</tr>
<tr>
<thead>
<tr>
<th>Total</th>
<th>{{RateTotal}}</th>
</tr>
</thead>
</tr>
</tbody>
</table>
P.S.
This directive can be abused to add unnecessary amounts of logic into
your templates. There are only a few appropriate uses of ngInit, such
as for aliasing special properties of ngRepeat, as seen in the demo
below; and for injecting data via server side scripting. Besides these
few cases, you should use controllers rather than ngInit to initialize
values on a scope. - ngInit
move this logic into the controller. That is what it is for. The view should be displaying data.
Now you have to worry about how to cast strings to an integer and writing 4x more code in a language that angular must interpret into javascript.
The complexity you are adding here is going to be fun to maintain.
but you probably want to continue doing it wrong, in which case this should work: <table ng-init='videos.total = {"rate": 0}'>
Define a filter to calculate the total:
app.filter('calculateRateTotal',function(){
return function(input){
var total = 0;
angular.forEach(input,function(value,key){
total = total+value.rate;
});
return total;
};
});
HTML:
<td ng-bind="videos | calculateRateTotal"></td>
After 10hrs of no luck just my managed to get it right. turned to be very simple.
This is the code.
In the Controller added
$scope.getTotal = function(){
var total = 0;
for(var i = 0; i < $scope.videos.length; i++){
var item = $scope.videos[i];
total += (item.rate*1);
}
return total; }
And HTML
<table>
<tr>
<th>Rate</th>
</tr>
<tr ng-repeat="item in videos">
<td>{{item.rate}}</td>
</tr>
<tr>
<td>Total: {{ getTotal() }}</td>
</tr>
</table>
Thanks everyone for helping

Sum of Inputs in ng-repeat

I'm trying to create a prototype that populates a list of unpaid invoices using ng-repeat. Within this, I am creating an input for each invoice. I want to be able to have a user input $ amounts into these inputs and then display a total of all inputs. Going off of this example: http://jsfiddle.net/d5ug98ke/9/ I cannot get it to work as it does in the fiddle. Here is my code:
<table class="table table-striped header-fixed" id="invoiceTable">
<thead>
<tr>
<th class="first-cell">Select</th>
<th class="inv-res2">Invoice #</th>
<th class="inv-res3">Bill Date</th>
<th class="inv-res4">Amount</th>
<th class="inv-res5">Amount to Pay</th>
<th class="inv-res6"></th>
</tr>
</thead>
<tbody>
<tr ng-if="invoices.length" ng-repeat="item in invoices | filter: {status:'Unpaid'}">
<td class="first-cell"><input type="checkbox" /></td>
<td class="inv-res2">{{item.invoiceNum}}</td>
<td class="inv-res3">{{item.creationDate}}</td>
<td class="inv-res4" ng-init="invoices.total.amount = invoices.total.amount + item.amount">{{item.amount | currency}}</td>
<td class="inv-res5">$
<input ng-validate="number" type="number" class="input-mini" ng-model="item.payment" ng-change="getTotal()" min="0" step="0.01" /></td>
</tr>
</tbody>
</table>
<table class="table">
<tbody>
<tr class="totals-row" >
<td colspan="3" class="totals-cell"><h4>Account Balance: <span class="status-error">{{invoices.total.amount | currency }}</span></h4></td>
<td class="inv-res4"><h5>Total to pay:</h5></td>
<td class="inv-res5">${{total}}</td>
<td class="inv-res6"></td>
</tr>
</tbody>
</table>
And the Angular:
myBirkman.controller('invoiceList', ['$scope', '$http', function($scope, $http) {
$http.get('assets/js/lib/angular/invoices.json').success(function(data) {
$scope.invoices = data;
});
$scope.sum = function(list) {
var total=0;
angular.forEach(list , function(item){
total+= parseInt(item.amount);
});
return total;
};
$scope.total = 0;
$scope.getTotal = function() {
$scope.invoices.forEach(function(item){
$scope.tot += parseInt(item.payment);
});
};
}]);
Any help would be appreciated. I dont necessarily need to use the method in the fiddle if someone has a better idea.
It seems there are two issues. First a simple typo:
$scope.tot += parseInt(item.payment, 10);
should be
$scope.total += parseInt(item.payment, 10);
And you should also reset $scope.total to 0 at the beginning of getTotal().
Edit: The way you did it, you always have to remember to update the total when something changes. Instead, you could let getTotal just return the total and write {{ getTotal() }} in the template. You don't have to trigger getTotal() in via ng-change then. If you don't have a lot of inputs you shouldn't worry about performance here.

Get total sum values within ng-repeat with angular js

I used ng-repeat to repeat json array. I calculated Night(s) by using dayDiff() function. Now I want to get total night all invoices. I am using angularjs.
How can I get total nights for all invoices?
<table class="table" ng-show="filteredItems > 0">
<tr>
<td>No</td>
<td>Invoice No</td>
<td>Name</td>
<td>Eamil</td>
<td>Room Name</td>
<td>Check In Date</td>
<td>Check Out Date</td>
<td>No. Room</td>
<td>Night(s)</td>
<td>Booking Date</td>
<td>Amount</td>
</tr>
<tr ng-repeat="data in filtered = (list | filter:search ) | startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit">
<td>{{$index+1}}</td>
<td>{{data.invoicenumber}}</td>
<td>{{data.firtname}}{{data.lastname}}</td>
<td>{{data.email}}</td>
<td>{{data.roomname}}</td>
<td ng-model='fromDate'>{{data.cidt}}</td>
<td ng-model='toDate'>{{data.codt}}</td>
<td>{{data.qty}}</td>
<td ng-model='night'>{{dayDiff(data.cidt,data.codt)}}</td>
<td>{{data.bdt}}</td>
<td>{{data.btotal}}</td>
</tr>
</table>
You need to add an extra row to begin with. This extra row will look like this:
<tr>
<td colspan="11">Total nights: {{calcTotal(filtered)}}</td>
</tr>
Then in your controller you need to add a function to calculate the nights like
$scope.calcTotal = function(filtered){
var sum = 0;
for(var i = 0 ; i<filtered.length ; i++){
sum = sum + filtered[i].nights;
}
return sum;
};
You could first, use a factory for your JSON model, to store the computed nights:
// We inject the dayDiff function via the dayDiffService service
angular.factory('invoice', ['dayDiffService', function(dayDiffService) {
var Invoice = function(data) {
// merge json properties to self
angular.merge(this, data);
// we compute the night(s)
this.nights = dayDiffService.dayDiff(data.cidt, data.codt);
}
return Invoice;
}]);
Then, in your controller, you add a function to sum up the nights from a filtered list:
angular.controller('invoicesCtrl', ['$scope', 'invoice', function($scope, Invoice) {
$scope.list = [];
// let's say that JSON holds your json model from http's response
$scope.list = JSON.map(function() {
return new Invoice(i)
});
$scope.sumNights = function(filtered) {
filtered.reduce(function(sum, invoice) {
sum += invoice.nights;
sum
}, 0);
}
}]);
Then, in your html you add a new row to display the computed result:
<div ng-controller="invoicesCtrl as vm">
<table>
...
<tbody>
<tr ng-repeat="data in filtered = (vm.list | filter:search ) | startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit">
<td>{{$index+1}}</td>
...
<tr>
</tbody>
<tfoot>
<tr>
<td colspan="8"></td
<td>{{vm.sumNights(filtered)}}</td
<td colspan="2"></td
</tr>
</tfoot>
</table>
</div>

Categories

Resources