Meteor - color highlight table row when date=today - meteor

i would like to highlight the date if match.datetime if equal to today, May I have some hints?
in .html
{{#each match in matches}}
<tr class="center aligned" bgcolor= "red">
<td>
{{match.datetime}}
</td>
</tr>
{{/each}}
in .js
Template.List_matches_page.helpers({
matches() {
return Matches.find({}, {sort: {datetime: -1}});
},
});

You can write a helper for that:
{{#each match in matches}}
<tr class="center aligned" bgcolor= "red">
<td class="{{#if isToday match.datetime}}color-bg{{/if}}">
{{match.datetime}}
</td>
</tr>
{{/each}}
const now = new Date()
const isToday = (date) =>
date.getFullYear() === now.getFullYear() &&
date.getMonth() === now.getMonth() &&
date.getDate() === now.getDate()
Template.List_matches_page.helpers({
matches() {
return Matches.find({}, {sort: {datetime: -1}});
},
isToday(date) {
return isToday(date)
}
});
If you have many places in your code, that require this check, you should rather use Template.registerHelper to avoid duplicate code in your templates: https://www.blazejs.org/api/templates.html#Template-registerHelper

Related

KnockoutJs : ko.mapping.fromJS and binding => how to do it properly?

I really am struggling with something that I thought was simple...
I am making a simple search-result table based on $.getJSON call, and want to keep my code as "generic" as possible.
In my (simplified) HTML :
<form id="searchForm">
(...)
<button type="button" onclick="search()">Search</button>
</form>
(...)
<tbody data-bind="foreach: data">
<tr>
<td data-bind="text: FOO"></td>
(...)
<td data-bind="text: BAR"></td>
</tr>
</tbody>
Then in my javascript (in script tags lower in the page):
var search = function(){
var form = $('#searchForm');
$.getJSON("php/query/jsonQuery.php?jsonQuery=search", form.serialize(), function(jsonAnswer, textStatus) {
console.log(jsonAnswer);
if(typeof viewModel === 'undefined'){
var viewModel = ko.mapping.fromJS(jsonAnswer);
ko.applyBindings(viewModel);
}
else{
ko.mapping.fromJS(jsonAnswer, viewModel);
}
$('#divResults').show();
// console.log(viewModel)
});
}
This works fine on the first "search" click... but not the following : Error You cannot apply bindings multiple times to the same element.
As you can guess, this very ugly "if" testing viewModel is a desperate attempt to get rid of that error.
I've tried many things but I just can't figure out how to do it properly...
I've read this Knockout JS update view from json model and this KnockoutJs v2.3.0 : Error You cannot apply bindings multiple times to the same element but it didn't help me much... maybe because the search() function isn't called on load (and indeed shouldn't be).
Any KO master to give me a clue? Thanks in advance for your help!
This is how I would be approaching what you are trying to accomplish.
var searchService = {
search: function(form, vmData) {
//$.getJSON("php/query/jsonQuery.php?jsonQuery=search", form.serialize(), function(jsonAnswer, textStatus) {
var jsonAnswer = [{
FOO: "Item 1 Foo",
BAR: "Item 1 Bar"
}, {
FOO: "Item 2 Foo",
BAR: "Item 2 Bar"
}]
ko.mapping.fromJS(jsonAnswer, [], vmData);
//})
}
};
var PageViewModel = function() {
var self = this;
self.data = ko.observableArray();
self.hasResults = ko.pureComputed(function() {
return self.data().length > 0;
});
self.search = function() {
var form = $('#searchForm');
searchService.search(form, self.data);
};
};
ko.applyBindings(new PageViewModel());
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<form id="searchForm">
<button type="button" data-bind="click:search">Search</button>
</form>
<div data-bind="visible: !hasResults()"><b>No Results</b></div>
<div data-bind="visible: hasResults">
<table class="table">
<thead>
<tr>
<td>FOO</td>
<td>BAR</td>
</tr>
</thead>
<tbody data-bind="foreach: data">
<tr>
<td data-bind="text: FOO"></td>
<td data-bind="text: BAR"></td>
</tr>
</tbody>
</table>
</div>
<br/>
<pre><code data-bind="text: ko.toJSON($root)"></code></pre>

Display row number using {{#each}}

I'm trying to count each row in a table. Each table row is a new collection. The code below counts the total number of collections and displays that. How do I change it to display the row number.
Path: calc.js
SalaryCalculator: function () {
return SalaryCalculator.find({});
},
SalaryCalculatorCount: function () {
return SalaryCalculator.find({}).count();
}
Path: calc.html
{{#each SalaryCalculator}}
<tr>
<th scope="row">{{SalaryCalculatorCount}}</th>
<td>{{specialisation}}</td>
<td>{{subSpecialisation}}</td>
<td>{{positionTitle}}</td>
<td>{{yearsOfExperience}}</td>
<td>{{salary}}</td>
</tr>
{{/each}}
Here's the helpers
SalaryCalculator: function () {
var count = 1;
var salCalDetails = SalaryCalculator.find({});
salCalDetails.forEach(function(doc){
doc.rowCount = count;
count++;
});
return salCalDetails;
},
{{#each SalaryCalculator}}
<tr>
<th scope="row">{{rowCount}} </th>
<td>{{specialisation}}</td>
<td>{{subSpecialisation}}</td>
<td>{{positionTitle}}</td>
<td>{{yearsOfExperience}}</td>
<td>{{salary}}</td>
</tr>
{{/each}}
Or if you follow through the answer given by #Michel Floyd then you need this answer too https://stackoverflow.com/a/22103990/3422755 as {{#index}} will give you starting number as 0

Pipe/Ajax plugin smart-table is not working

I just taked the default example from
https://lorenzofox3.github.io/smart-table-website/#section-pipe
but it doesn't work, I code copied from the example, and assigned in the code the app: ng-app="myApp", and a controller: ng-controller="pipeCtrl as mc" to make it work, no errors shown in console
I also added some console.log prints, to know when the specific code lines are executed, and I see the next in console:
pushed it
ctr init
here is the code:
var app = angular.module('myApp', ['smart-table']);
app.controller('pipeCtrl', ['Resource', function (service) {
var ctrl = this;
console.log("ctr init");
this.displayed = [];
this.callServer = function callServer(tableState) {
console.log("callserv");
ctrl.isLoading = true;
var pagination = tableState.pagination;
var start = pagination.start || 0; // This is NOT the page number, but the index of item in the list that you want to use to display the table.
var number = pagination.number || 10; // Number of entries showed per page.
service.getPage(start, number, tableState).then(function (result) {
console.log("getP");
ctrl.displayed = result.data;
tableState.pagination.numberOfPages = result.numberOfPages;//set the number of pages so the pagination can update
ctrl.isLoading = false;
});
};
}]);
app.factory('Resource', ['$q', '$filter', '$timeout', function ($q, $filter, $timeout) {
var randomsItems = [];
function createRandomItem(id) {
var heroes = ['Batman', 'Superman', 'Robin', 'Thor', 'Hulk', 'Niki Larson', 'Stark', 'Bob Leponge'];
return {
id: id,
name: heroes[Math.floor(Math.random() * 7)],
age: Math.floor(Math.random() * 1000),
saved: Math.floor(Math.random() * 10000)
};
}
for (var i = 0; i < 1000; i++) {
randomsItems.push(createRandomItem(i));
}
console.log("pushed it");
//fake call to the server, normally this service would serialize table state to send it to the server (with query parameters for example) and parse the response
//in our case, it actually performs the logic which would happened in the server
function getPage(start, number, params) {
var deferred = $q.defer();
console.log("getting p svc");
var filtered = params.search.predicateObject ? $filter('filter')(randomsItems, params.search.predicateObject) : randomsItems;
if (params.sort.predicate) {
filtered = $filter('orderBy')(filtered, params.sort.predicate, params.sort.reverse);
}
var result = filtered.slice(start, start + number);
$timeout(function () {
console.log("timeout");
//note, the server passes the information about the data set size
deferred.resolve({
data: result,
numberOfPages: Math.ceil(filtered.length / number)
});
}, 1500);
return deferred.promise;
}
return {
getPage: getPage
};
}]);
The page html rendered in asp.net mvc:
#section scripts {
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/app1.js"></script>
<script src="~/Scripts/smart-table.js"></script>
}
<div class="row" ng-app="myApp">
<div class="col-md-12">
<h2>Smart Ajax Data Tables</h2>
<p ng-controller="pipeCtrl as mc">
<table class="table" st-pipe="mc.callServer" st-table="mc.displayed">
<thead>
<tr>
<th st-sort="id">id</th>
<th st-sort="name">name</th>
<th st-sort="age">age</th>
<th st-sort="saved">saved people</th>
</tr>
<tr>
<th><input st-search="id" /></th>
<th><input st-search="name" /></th>
<th><input st-search="age" /></th>
<th><input st-search="saved" /></th>
</tr>
</thead>
<tbody ng-show="!mc.isLoading">
<tr ng-repeat="row in mc.displayed">
<td>{{row.id}}</td>
<td>{{row.name}}</td>
<td>{{row.age}}</td>
<td>{{row.saved}}</td>
</tr>
</tbody>
<tbody ng-show="mc.isLoading">
<tr>
<td colspan="4" class="text-center">Loading ... </td>
</tr>
</tbody>
<tfoot>
<tr>
<td class="text-center" st-pagination="" st-items-by-page="10" colspan="4"></td>
</tr>
</tfoot>
</table>
</p>
</div>
</div>

Meteor: Count data from collection

anyone please i need you help. before this I have asking question but I cannit find this solution. I have create code to count variable in collection. I can get the result when count one by one but not by group. Thats my code, I want to count this but the code not given any resut to me. I want the result like this:
PTR 1
KOM 4
This my code:
<template name="laporankategori">
<table class="table">
<thead>
<tr>
<th>Jenis Peralatan</th>
<th>Kuantiti</th>
</tr>
</thead>
<tbody>
{{#each profil}}
<tr>
<td>{{PTR}}</td>
<td>{{KOM}}</td>
</tr>
{{/each}}
</tbody>
</table>
</template>
//js
Template.laporankategori.helpers({
profil: function() {
return Profil.find({kategori: { $in: ['PTR', 'KOM'] } }).count();
}
});
<template name="laporankategori">
<table class="table">
<thead>
<tr>
<th>Jenis Peralatan</th>
<th>Kuantiti</th>
</tr>
</thead>
<tbody>
{{#each profil}}
<tr>
<td>{{count}}</td>
</tr>
{{/each}}
</tbody>
</table>
</template>
//js
Template.laporankategori.helpers({
profil: function() {
var PTR = {
count: Profil.find({kategori: { $in: ['PTR'] } }).count()
};
var KOM = {
count : Profil.find({kategori: { $in: ['KOM'] } }).count()
};
var resultArr = [PTR, KOM];
return resultArr;
}
});
Whenever you're iterating with {{#each ...}} your helper should return either a cursor or an array. Your helper is returning a scalar: the count. In your {{#each }} block you refer to {{PTR}} and {{KOM}} but those won't exist.
I suspect that you weren't actually looking for the count in this case and your helper should just be:
Template.laporankategori.helpers({
profil: function() {
return Profil.find({kategori: { $in: ['PTR', 'KOM'] } });
}
});
Also you don't often need to count things in a helper since in a template you can refer to {{profil.count}} and get the count of the cursor directly.

MeteorJS: Put date in dynamic template

WHAT I WANT TO BUILD IN DOM:
<table>
<tr> Today </tr>
<tr>
//data from Mongo
</tr>
...
<tr> Yesterday </tr>
....
//data from Mongo
..etc
</table>
CODE I HAVE :
<table>
{{#each posts}}
{{> postJobs}}
{{/each}}
</table>
<template name="postJobs">
<tr>
... // data from Mongo
</tr>
</template>
I think that it is necessary to compare the date from Mongo documents and today date or something like this.
Any idea how to build this ?
I guess you are requesting how to get the documents from collections grouped by date.
So on Top to see today chat, next block Yesterday, next block Previous Chats
Just call 3 times the same template
<template name="main">
<h1>Today</h1>
{{> list_posts posts=today}}
<h1>Yesterday</h1>
{{> list_posts posts=yesterday}}
<h1>Previous</h1>
{{> list_posts posts=previous}}
</template>
<template name="list_posts">
<table>
{{#each posts}}
<tr>
<td>{{col1}}</td>
<td>{{colX}}</td>
</tr>
{{/each}}
</table>
</template>
And then you need this helpers
Template.main.helpers({
today: function() {
return Posts.find() // col.date >= today
},
yesterday: function() {
return Posts.find() // col.date < today and >= yesterday
},
previous: function() {
return Posts.find() // col.date < yesterday
}
});
Good luck
Tom
I don't get what you exactly want to achieve. Comparing to today date would look like this, in an helper (that you can use in an {{#if compareDate}} statement:
compareDate: function(){
var today= new Date(new Date().getTime());
return this.date < today// it will get you true is the date field of your mongo document is older than today
}
Extra info, if you need yesterday:
var yesterday = new Date(new Date().getTime() - (24 * 60 * 60 * 1000));

Resources