Getting total of a row Angularjs - javascript

Hi I have a simple row that I am trying to display the total of.
In my html I have
<tr ng-repeat="item in items">
<td>{{item.name}}</td>
<td ng-init="iTotal= iTotal + item.price">{{item.price}}</td>
</tr>
<tr>
<td></td>
<td>Total :</td>
<td>Total:{{iTotal}}</td>
</tr>
In my controller I have
var vm=this;
vm.Itotal=0;
This basically doesn't gives me blank for iTotal no error.
Please let me know how to fix it to get the result. Thanks

If you are using view model annotation:
var vm=this;
vm.Itotal=0;
Then you should access vm.Itotal like this:
<td ng-init="controller.Itotal = controller.Itotal + item.price">{{item.price}}</td>
Pay attention that you use iTotal in your view and Itotal (I in uppercase) in your controller.

You can try this simple way:
Demo plunker
HTML:
<table>
<tr ng-repeat="item in items">
<td>{{item.name}}</td>
<td >{{item.price}}</td>
</tr>
<tr>
<td></td>
<td>Total:{{iTotal}}</td>
</tr>
</table>
JS:
$scope.items=[{
"id": 1,
"price": 12,
},
{
"id": 1,
"price": 1,
}];
$scope.iTotal=0;
$scope.items.forEach(function(i){
$scope.iTotal= $scope.iTotal + i.price;
})

JSFiddle explaining the same: (Not created by me, Copied from JSFiddle)
http://jsfiddle.net/J9Aj8/
angular.module("app", []).
filter("sum", function sum$$factory() {
return function sum$$filter(collection) {
var sum = 0;
_.forOwn(collection, function(value) {
switch (typeof value) {
case 'number': sum += value; break;
case 'string': sum += (value >>> 0); break;
default: // don't know what to do with this, maybe something else!
break;
}
});
return sum;
};
}).
controller("itemsCtrl", function() {
var self = this;
this.model = {};
this.numbers = [
36,
72,
80,
101,
9,
42
];
this.addNumber = function() {
var value = self.model.newNumber;
if (value === value && typeof value === 'number') {
self.numbers.push(value);
self.model.newNumber = NaN;
}
};
});

Related

AngularJs ng-repeat add Color to the largest value of the cell in the respected column

I am new to Angularjs,
and do not know how to accomplish this.
I would like to add color to the member with the biggest Score, Missed, field Goal percentage.
is this possible?
is there a way to change the color of value to green of the member with the largest value of each column.
like this:(desired result)
this is my html code :
<body ng-app="myApp" ng-controller="myCtrl">
<table border="2">
<tr>
<th>Members</th>
<th>Score</th>
<th>Missed</th>
<th>FG%</th>
</tr>
<tr ng-repeat="member in members">
<td>{{member.name}}</td>
<td>{{getScore(member.shotMade)}}</td>
<td>{{getMissed(member.shotMade, member.shotAttemp)}}</td>
<td>{{getFG(member.shotMade, member.shotAttemp)}}</td>
</tr>
</table>
this is my javascript code:
const app = angular.module('myApp', []);
app.controller('myCtrl', function($scope){
$scope.test = "success";
$scope.members =
[
{name:'Kobe', shotMade:23, shotAttemp:44},
{name:'lebron', shotMade:21, shotAttemp:33},
{name:'Jordan', shotMade:32, shotAttemp:43},
{name:'Hakeem', shotMade:20, shotAttemp:21},
]
$scope.getScore = (made)=> made * 2;
$scope.getMissed = (made, attemp) => attemp - made;
$scope.getFG = (made, attemp) => (made / attemp) * 10000;
});
is there a way to do this with angularjs or Javascript?
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.members = [
{ name: 'Kobe', shotMade: 23, shotAttemp: 44 },
{ name: 'lebron', shotMade: 21, shotAttemp: 33 },
{ name: 'Jordan', shotMade: 32, shotAttemp: 43 },
{ name: 'Hakeem', shotMade: 20, shotAttemp: 21 }
]
var getScore = (made) => made * 2;
var getMissed = (made, attemp) => attemp - made;
var getFG = (made, attemp) => (made / attemp) * 10000;
$scope.maxScore = 0;
$scope.maxMissed = 0;
$scope.maxFG = 0;
for (var member of $scope.members) {
member.score = getScore(member.shotMade);
if (member.score > $scope.maxScore)
$scope.maxScore = member.score;
member.missed = getMissed(member.shotMade, member.shotAttemp);
if (member.missed > $scope.maxMissed)
$scope.maxMissed = member.missed;
member.fg = getFG(member.shotMade, member.shotAttemp);
if (member.fg > $scope.maxFG)
$scope.maxFG = member.fg;
}
});
.maxGreen {
color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js">
</script>
<body ng-app="myApp" ng-controller="myCtrl">
<table border="2">
<tr>
<th>Members</th>
<th>Score</th>
<th>Missed</th>
<th>FG%</th>
</tr>
<tr ng-repeat="member in members">
<td>{{member.name}}</td>
<td ng-class='{maxGreen: member.score == maxScore}'>{{member.score}}</td>
<td ng-class='{maxGreen: member.missed == maxMissed }'>{{member.missed}}</td>
<td ng-class='{maxGreen: member.fg == maxFG}'>{{member.fg}}</td>
</tr>
</table>

setting td inner text through script called in razor

I want to do something like this within my view (razor)
if(index == #:{<script>{getPosition(#geResult.assessmentId);}</script>}){
geResult.ResultValue;
}
What will be the proper syntax?
Full HTML
<tr>
#{
var index = 4;
foreach(Assessment geAssessment in Model.assessments)
{
<td>
#foreach (ShortResult geResult in Model.results)
{
if(geResult.StudentID == geStudent.studentid)
{
if(index == #:{<script>{getPosition(#geResult.assessmentId);}</script>} ){
geResult.ResultValue;
}
}
}
</td>
index++;
}
}
</tr>
UPDATE
I am trying the other way round now can anyone guide me please
SCRIPT
function getPosition(id, colIndex) {
var element = '#' + id;
$(this).closest('tr').find('td').eq(colIndex).html("A");
alert($(this).closest('tr').find('td').eq(colIndex).html());
return $(element).index();
}
HTML
<td>
#foreach (ShortResult geResult in Model.results)
{
if(geResult.StudentID == geStudent.studentid)
{
<script>{ getPosition(#geResult.assessmentId, #index); }</script>
}
}
</td>
now the alert returns undefined although i am setting its value (text) just before!!
Finally, after wasting a whole 1.5 days i am able to solve this! hope it helps someone.
SCRIPT
function getPosition(id, colIndex, resultValue) {
var element = '#' + id;
var cell = $('.test').closest('tr').children('td').get(colIndex);
if($(element).index() == colIndex){
cell.innerHTML = resultValue;
}
}
HTML
<tr>
#{
var index = 4;
foreach(Assessment geAssessment in Model.assessments)
{
<td class="test">
#foreach (ShortResult geResult in Model.results)
{
if(geResult.StudentID == geStudent.studentid)
{
if (geResult.ResultValue != null) {
<script>{ getPosition(#geResult.assessmentId, #index, '#geResult.ResultValue'); }</script>
}
}
}
</td>
index++;
}
}
</tr>

Get highest value from <td> in table by class

How can I get the highest value in a table column by class? I have tried the following:
HTML
<table>
<tr><td class="speed">1.1</td></tr>
<tr><td class="speed">3.1</td></tr>
<tr><td class="speed">5.5</td></tr>
<tr><td class="speed">2.0</td></tr>
</table>
jQuery/Javascript
function gethighestspeeds(){
var speeds = $(".speed").map(function() {
return parseFloat(this.text, 10);
}).get();
var highestspeed = Math.max.apply(Math, speeds);
alert(highestspeed)
}
Also, how can I get all values if > than a certain number?
this.text is undefined for the td element, you need to parse parseFloat($(this).text(), 10);
function gethighestspeeds() {
var speeds = $(".speed").map(function() {
return parseFloat($(this).text(), 10);
}).get();
var highestspeed = Math.max.apply(Math, speeds);
snippet.log('high: ' + highestspeed);
var num = 2.3;
var array = $(".speed").map(function() {
var flt = parseFloat($(this).text(), 10);
return flt > num ? flt : undefined;
}).get();
snippet.log('array: ' + array)
//if you already have the speeds array
var array2 = speeds.filter(function(val) {
return num < val;
});
snippet.log('array2: ' + array)
}
gethighestspeeds();
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="speed">1.1</td>
</tr>
<tr>
<td class="speed">3.1</td>
</tr>
<tr>
<td class="speed">5.5</td>
</tr>
<tr>
<td class="speed">2.0</td>
</tr>
</table>
Try this........
var certainNumber=2.2; //Whatever you want to set
function gethighestspeeds(){
var speeds = $(".speed").map(function() {
return parseFloat(this.text, 10) > parseFloat(certainNumber);
}).get();
}
You have to use : $(this).text() instead of this.text in your map function:
return parseFloat($(this).text(), 10);

Populate table from JSON with search

I was able to purely implement a grid from a JSON object - AngularJS ng-repeat to populate grid from array. However, due to the nature of the added indices, being able to create a search bar with ng-model and filter:search does not work - it only can search for the first in each table row.
var test= angular.module("app", []);
test.controller("appControl", function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function (response) {
$scope.data = response.records;
}
);
$scope.getFiltered= function(obj, idx){
//Set a property on the item being repeated with its actual index
//return true only for every 1st item in 5 items
return !((obj._index = idx) % 5);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<body ng-app='app' ng-controller='appControl'>
<input type='text' ng-model='search.Country' />
<table>
<tr ng-repeat="work in data | filter:getFiltered | filter:search">
<td>{{work.Country}}</td>
<td>{{data[work._index+1].Country}}</td>
<td>{{data[work._index+2].Country}}</td>
<td>{{data[work._index+3].Country}}</td>
<td>{{data[work._index+4].Country}}</td>
</tr>
</table>
</body>
The length of data may or not cause the table to look like a perfect rectangle.
I'm working on making a function to split up the array and create the grid in JavaScript itself, but I'm still not sure how to filter it via search input.
Second try (with the mentioned function, but no filters at all yet...):
var test= angular.module("app", []);
function createGrid(arr, width) {
newArr = [];
reps = Math.ceil(arr.length/width) * width;
k = 0;
for (var i = 0; i < reps/width; i++) {
newArr[i] = [];
}
for (var i = 0; i < reps/width; i++) {
for (var j = 0; j < width; j++) {
(arr[k]) ? newArr[i][j] = arr[k] : newArr[i][j] = "";
//console.log(i, j, arr[k]);
k++;
}
}
return newArr;
}
test.controller("appControl", function($scope, $http) {
$scope.gridWidth = 4;
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function (response) {
$scope.data = createGrid(Object.keys(response.records).map(function(k) { return response.records[k] }), $scope.gridWidth);
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<body ng-app='app' ng-controller='appControl'>
<input type='text' ng-model='search.Country' />
<table>
<tr ng-repeat="row in data">
<td ng-repeat='work in row'>
{{ work.Country }}
</td>
</tr>
</table>
</body>
You could try something like this:
var test= angular.module("app", []);
test.controller("appControl", function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function (response) {
$scope.data = response.records;
$scope.filteredData= response.records;
}
);
$scope.$watch('search', function () {
var array=[];
for(var i in $scope.data)
{
if($scope.search==undefined || $scope.search.length == 0 || ($scope.data[i].Country!=undefined&&$scope.data[i].Country.toUpperCase().startsWith($scope.search.toUpperCase()))){
array.push($scope.data[i]);
}
}
$scope.filteredData=array;
});
$scope.getFiltered= function(obj, idx){
//Set a property on the item being repeated with its actual index
//return true only for every 1st item in 3 items
return !((obj._index = idx) % 5);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<body ng-app='app' ng-controller='appControl'>
<input type='text' ng-model='search' />
<table>
<tr ng-repeat="work in filteredData | filter:getFiltered | filter:search">
<td>{{work.Country}}</td>
<td ng-show="filteredData[work._index+1]">{{filteredData[work._index+1].Country}}</td>
<td ng-show="filteredData[work._index+2]">{{filteredData[work._index+2].Country}}</td>
<td ng-show="filteredData[work._index+3]">{{filteredData[work._index+3].Country}}</td>
<td ng-show="filteredData[work._index+4]">{{filteredData[work._index+4].Country}}</td>
</tr>
</table>
</body>
You could prefilter the items after a successful Ajax call and every time your model search changes.
Save the previously filtered items into $scope.workers.
Use $scope.$watch to watch for changes in the model search
Use the function searched(data) to filter for the entries that have characters given in the search field using the indexOf method. If the filter is empty, also show every item (typeof $scope.search == 'undefined').
If you want the search be case insensitive, transform searchand the Country .toLowerCase(), when using .indexOf()
Then you will only need one Angular filter $scope.getFiltered(), which makes sure, that the entries are in rows of five.
var test= angular.module("app", []);
test.controller("appControl", function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function (response) {
$scope.data = response.records;
$scope.workers = $scope.searched($scope.data);
}
);
$scope.getFiltered= function(obj, idx){
//Set a property on the item being repeated with its actual index
//return true only for every 1st item in 5 items
return !((obj._index = idx) % 5);
};
$scope.searched = function (data) {
var array = [];
var max = 0;
if (typeof data === 'object') {
max = data.length;
}
for (var i = 0; i < max; i += 1) {
if (typeof $scope.search == 'undefined' || data[i].Country.toLowerCase().indexOf($scope.search.toLowerCase()) != -1) {
array.push(data[i]);
}
}
return array;
};
$scope.$watch('search', function () {
$scope.workers = $scope.searched($scope.data);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<body ng-app='app' ng-controller='appControl'>
<input type='text' ng-model='search' />
<table>
<tr ng-repeat="work in workers | filter:getFiltered">
<td>{{ work.Country }}</td>
<td>{{ workers[$index+1].Country }}</td>
<td>{{ workers[$index+2].Country }}</td>
<td>{{ workers[$index+3].Country }}</td>
<td>{{ workers[$index+4].Country }}</td>
</tr>
</table>
</body>

Load Image Instead of link?

I have been trying out different methods of how to load an image, I was trying to load the image from a web address but instead of loading the image its just loading the link to the address? I have updated the code which is below (just the sections for loading the cards) however it still only loads the link not the image? Can anyone see where i am going wrong?
card js (there are more cards than 2 but for this example I only added two)
GABIH20.cards = (function(){
var public_stuff = {};
var cards = [
{name: "Gabi H20", energy: 90, saving: 99, eco: 98, ease: 89, image: 'http://www.lessons4living.com/images/penclchk.gif'},
{name: "Sherlock H20lmes", energy: 30, saving: 70, eco: 35, ease: 60, image:'http://www.sherlock.com/images/penclchk.gif'},
];
var shuffle = function(v){
//This is just random code I plucked from the Internet. Seems to work for this purpose.
for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
return v;
}
public_stuff.get_cards = function() {return cards;}
public_stuff.deal_hands = function() {
var half_way_point = cards.length / 2;
var shuffled_deck = shuffle(cards);
return [cards.slice(0, half_way_point), cards.slice(half_way_point)];
}
return public_stuff;
}());
event js
GABIH20 = {};
GABIH20.game = (function(){
var num_rounds_played_in_this_game = 0;
var playing_game = false;
var player, opponent, player_name;
var public_stuff = {};
public_stuff.current_view = "#menu_view";
var populate_card_view = function(player) {
var card = player.get_current_card();
$("header .distro_name").html(card.name);
$(".attr_image .attr_imgvalue").html(card.image);
$(".attr_energy .attr_value").html(card.energy);
$(".attr_saving .attr_value").html(card.saving);
$(".attr_eco .attr_value").html(card.eco);
$(".attr_ease .attr_value").html(card.ease);
}
public_stuff.playing_game = function() {
return playing_game;
}
public_stuff.get_player_name = function() {
return player_name;
}
HTML
<div id="card_view" class="app_view">
<header>
<p>You drew the <span class="distro_name">Ubuntu</span> card</p>
</header>
<div class="distro_info">
<table class="distro_attributes">
<tr class="distro_attribute attr_image">
<td class="attr_imgvalue"><img src="" class="card_image" /></td>
</tr>
</table>
</div>
<p><strong>Now choose an attribute to battle with!</strong></p>
<table class="distro_attributes">
<tr class="distro_attribute attr_energy">
<td class="attr_name">Energy</td>
<td class="attr_value">100</td>
</tr>
<tr class="distro_attribute attr_saving">
<td class="attr_name">Saving</td>
<td class="attr_value">100</td>
</tr>
<tr class="distro_attribute attr_eco">
<td class="attr_name">Eco</td>
<td class="attr_value">100</td>
</tr>
<tr class="distro_attribute attr_ease">
<td class="attr_name">Ease</td>
<td class="attr_value">100</td>
</tr>
</table></div>
Change the line,
$(".attr_image .attr_imgvalue").html(card.image);
to
$(".attr_image .attr_imgvalue img").attr('src',card.image); // add link to img src

Categories