-ISSUE- AngularMeteor,Meteor or Angular - angularjs

thanks for read
Comportamientos:
when the result verCandidatos.postulados only have one value (like rectangle in img) never print the first time, I need refresh or click again and print values why?
html client
my-app/imports/ui/components/vacantes/verCandidatos/verCandidatos.html
<div ng-repeat="postulado in verCandidatos.postulados">
{{postulado.candidato().nombre}}
{{postulado.candidato().apellidos}}
{{postulado.candidato().sexo}}
</div>
Next the images:
//////////// ISUE img1
//////////// ISUE img2
js in client
my-app/imports/ui\components/vacantes/verCandidatos/verCandidatos.js
imports ...
class VerCandidatos {
constructor($scope, $reactive, $stateParams) {
'ngInject';
$reactive(this).attach($scope);
this.vacanteId = $stateParams.vacanteId;
this.subscribe('vacantes.candidatosOseleccionados', ()=>
[
{vacanteId: this.vacanteId},
{estado: 1}
]
);
this.helpers({
postulados (){
return Postulaciones.find();
}
});
}
}
collection.js
my-app/imports/api/postulaciones/collection.js
imports...
export const Postulaciones = new Mongo.Collection('postulaciones');
Postulaciones.deny({...});
Postulaciones.helpers({
candidato(){
return Candidatos.findOne({_id: this.candidatoId});
}
});
publish.js:
my-app/imports/api/vacantes/server/publish.js
imports...
if (Meteor.isServer) {
Meteor.publishComposite('vacantes.candidatosOseleccionados', function (vacanteId, estado) {
const selector = {$and: [estado, vacanteId]};
return {
find: function () {
return Postulaciones.find(selector);
},
children: [
{
find: function (postulacion) {
return Candidatos.find({_id: postulacion.candidatoId}, {
fields: {
nombre: 1,
apellidos: 1,
sexo: 1,
}
});
}
}
]
};
});
}
Any ideas?
- Thanks,

Related

Iterate over data() returned value

My HTML code is like below
<ul>
<li v-for="item in values">{{ item }}</li>
</ul>
My vue.js code is like below
export default {
data() {
return {
values: {}
}
},
props: ['applicants', 'pageinfo'],
watch: {
applicants (val) {
EventBus.$on('click', function (skillName) {
this.values = val[0];
console.log(this.values); // I am getting output here.
});
},
},
}
I am trying to iterate over the values of val[0]. But I am not getting any output.
Either use arrow function like
applicants (val) {
EventBus.$on('click', (skillName) => {
this.values = val[0];
console.log(this.values); // I am getting output here.
});
},
or save the reference of this before the event handler
applicants (val) {
var _self = this;
EventBus.$on('click', function (skillName) {
_self.values = val[0];
console.log(this.values); // I am getting output here.
});
},

Specifying default extensions in angular2 and ng2-table

I am trying to use ng2-table in my angular2 project. I installed angular2 and ng2-table using npm, when I run my app I get this 404 errors.
But the files exist in my project!
the server is looking for files with no extension, is there any way to specify default extension?
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms'; // <-- NgModel lives here
import {Ng2TableModule} from "ng2-table";
import { JobsComponent } from './components/jobs/jobs.component';
import { JobsTable } from './components/jobs/jobs.component';
#NgModule({
imports: [
BrowserModule,
FormsModule, // <-- import the FormsModule before binding with [(ngModel)]
Ng2TableModule
],
declarations: [
JobsComponent,
JobsTable
],
bootstrap: [ JobsComponent,JobsTable ]
})
export class AppModule { }
jobs.components.ts
import {Component, OnInit} from '#angular/core';
#Component({
selector: 'jobs',
templateUrl: "./jobs.html"
})
export class JobsComponent {
}
export class JobsTable implements OnInit{
public rows:Array<any> = [];
public columns:Array<any> = [
{title: 'Name', name: 'name', filtering: {filterString: '', placeholder: 'Filter by name'}},
{
title: 'Position',
name: 'position',
sort: false,
filtering: {filterString: '', placeholder: 'Filter by position'}
},
{title: 'Office', className: ['office-header', 'text-success'], name: 'office', sort: 'asc'},
{title: 'Extn.', name: 'ext', sort: '', filtering: {filterString: '', placeholder: 'Filter by extn.'}},
{title: 'Start date', className: 'text-warning', name: 'startDate'},
{title: 'Salary ($)', name: 'salary'}
];
public page:number = 1;
public itemsPerPage:number = 10;
public maxSize:number = 5;
public numPages:number = 1;
public length:number = 0;
public config:any = {
paging: true,
sorting: {columns: this.columns},
filtering: {filterString: ''},
className: ['table-striped', 'table-bordered']
};
private data:Array<any> = null;
public constructor() {
this.length = this.data.length;
}
public ngOnInit():void {
this.onChangeTable(this.config);
}
public changePage(page:any, data:Array<any> = this.data):Array<any> {
let start = (page.page - 1) * page.itemsPerPage;
let end = page.itemsPerPage > -1 ? (start + page.itemsPerPage) : data.length;
return data.slice(start, end);
}
public changeSort(data:any, config:any):any {
if (!config.sorting) {
return data;
}
let columns = this.config.sorting.columns || [];
let columnName:string = void 0;
let sort:string = void 0;
for (let i = 0; i < columns.length; i++) {
if (columns[i].sort !== '' && columns[i].sort !== false) {
columnName = columns[i].name;
sort = columns[i].sort;
}
}
if (!columnName) {
return data;
}
// simple sorting
return data.sort((previous:any, current:any) => {
if (previous[columnName] > current[columnName]) {
return sort === 'desc' ? -1 : 1;
} else if (previous[columnName] < current[columnName]) {
return sort === 'asc' ? -1 : 1;
}
return 0;
});
}
public changeFilter(data:any, config:any):any {
let filteredData:Array<any> = data;
this.columns.forEach((column:any) => {
if (column.filtering) {
filteredData = filteredData.filter((item:any) => {
return item[column.name].match(column.filtering.filterString);
});
}
});
if (!config.filtering) {
return filteredData;
}
if (config.filtering.columnName) {
return filteredData.filter((item:any) =>
item[config.filtering.columnName].match(this.config.filtering.filterString));
}
let tempArray:Array<any> = [];
filteredData.forEach((item:any) => {
let flag = false;
this.columns.forEach((column:any) => {
if (item[column.name].toString().match(this.config.filtering.filterString)) {
flag = true;
}
});
if (flag) {
tempArray.push(item);
}
});
filteredData = tempArray;
return filteredData;
}
public onChangeTable(config:any, page:any = {page: this.page, itemsPerPage: this.itemsPerPage}):any {
if (config.filtering) {
Object.assign(this.config.filtering, config.filtering);
}
if (config.sorting) {
Object.assign(this.config.sorting, config.sorting);
}
let filteredData = this.changeFilter(this.data, this.config);
let sortedData = this.changeSort(filteredData, this.config);
this.rows = page && config.paging ? this.changePage(page, sortedData) : sortedData;
this.length = sortedData.length;
}
public onCellClick(data: any): any {
console.log(data);
}
}
Fixed by adding some few lines to systemjs.config.js,
/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
'app': 'app',
// angular bundles
'#angular/animations' : 'npm:#angular/animations/bundles/animations.umd.js',
'ng2-table' : 'npm:ng2-table/ng2-table.js',
'systemjs' : 'npm:systemjs/dist/systemjs.js'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
......
.....
// this specify default extension for ng2-table
'ng2-table': {
format: 'register', defaultExtension: 'js'
}
}
});
})(this);

JSON re-grouping with for each method in AngularJs

I am new in angular and i want to re-group a JSON. Is it possible to do with angular.forEach() method?
[
{
"doc":{
"Title":"Main",
"name":"Ajith",
"Day":"03",
"count":3
}
},
{
"doc":{
"Title":"starters",
"name":"Saji",
"Day":"01",
"count":39
}
},
{
"doc":{
"Title":"desert",
"name":"Sajeeb",
"Day":"02",
"count":63
}
},
{
"doc":{
"Title":"Main",
"name":"Suith",
"Day":"03",
"count":3
}
},
{
"doc":{
"Title":"starters",
"name":"Manu",
"Day":"01",
"count":9
}
}
]
I want the output should be like following.
{
"order":[
{
"Day":"01",
"Title":"starters",
"items":[
{
"name":"Saji",
"count":39
},
{
"name":"Manu",
"count":9
}
]
},
{
"Day":"02",
"Title":"desert",
"items":[
{
"name":"Sajeeb",
"count":63
}
]
},
{
"Day":"03",
"Title":"Main",
"items":[
{
"name":"Ajith",
"count":3
},
{
"name":"Suith",
"count":3
}
]
}
]
}
To regroup with angular.forEach() method.
Please help. Thanks.
https://jsfiddle.net/9fwtm0a0/4/
var days = [];
arr.forEach(function(d) {
var day = parseInt(d.doc.Day);
var item = { name: d.doc.name, count: d.doc.count };
if (days[day])
days[day].items.push(item);
else
days[day] = { Day: '0' + day, Title: d.doc.Title, items: item]};
});
days.sort(function (x, y) {
return parseInt(x.Day) > parseInt(y.Day);
});
var eventsinOrder = { order: days };
You don't really need the Angular forEach but you can easily substitute it in:
var days = [];
angular.forEach(arr, function (val, key) {
var day = parseInt(val.doc.Day);
var item = { name: val.doc.name, count: val.doc.count };
if (days[day])
days[day].items.push(item);
else
days[day] = { Day: '0' + day, Title: val.doc.Title, items: [item]};
});
days.sort(function (x, y) {
return parseInt(x.Day) > parseInt(y.Day);
});
var eventsinOrder = { order: days };
Either way you go you will still need to make use of the sort function (or any equivalent) to perform the sorting while you're building this resultant object.

AngularJS Typescript Controller Values not updating page

I'm picking up Angular for the first time and coming from a .NET backround feel a lot more comfortable working with typescript.
I've got a problem where a cant seem to get values to update on a page when a controller populates the controller values with an object received from a service. I'm probably just making a noob error.
Can anyone give a pointer on what I'm doing wrong.
So my typescript is
module ConnectAdmin.Interfaces {
export interface ITemplate {
templateId: number;
name: string;
description: string;
}
}
module ConnectAdmin.Interfaces {
export interface ITemplateCollection {
total: number;
set: number;
skipped: number;
collection: Array<ITemplate>;
}
}
module ConnectAdmin.Controllers {
import TemplateCollection = Interfaces.ITemplateCollection;
export class TemplateIndexController {
static $inject = ["ConnectAdmin.Services.TemplateService"];
constructor(templateService: ConnectAdmin.Services.TemplateService) {
this.defaultTemplates = { skipped: 0, set: 0, total: 0, collection: [] };
this.templates = this.defaultTemplates;
this.processing = true;
this.store = this;
templateService.index(this.take, this.skip, this.successCallback, this.errorCallback);
this.processing = false;
}
successCallback(data: TemplateCollection) {
this.templates = { skipped: 0, set: 0, total: 0, collection: [] }
this.templates = data;
alert(this.templates.collection.length);
}
errorCallback(response: any) {
this.templates = this.defaultTemplates;
alert(response.status);
this.message = "An Error Occurred Contacting the API";
}
processing: boolean;
store = this;
defaultTemplates: TemplateCollection;
templates: TemplateCollection;
take = 20;
skip = 0;
message: string;
}
angular.module("ConnectAdmin").controller("ConnectAdmin.Controllers.TemplateIndexController", TemplateIndexController);
}
module ConnectAdmin.Services {
import TemplateCollection = Interfaces.ITemplateCollection;
import TemplateIndexController = Controllers.TemplateIndexController;
export class TemplateService {
constructor($http: ng.IHttpService) {
this.http = $http;
}
http: ng.IHttpService;
index(take: number, skip: number, successCallback: Function, errorCallback: Function) {
const req = {
method: "GET",
url: "https://localhost:44336/api/Templates?take=" + take + "&skip=" + skip,
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
};
this.http(req).then(response => {
successCallback(response.data);
},
response => {
errorCallback(response);
});
//return { total: 1, skipped: 0, set: 1, collection: [{ templateId: 1, name: "Template 1", description: "" }] };
}
}
angular.module("ConnectAdmin").service("ConnectAdmin.Services.TemplateService", TemplateService);
}
with my html being:
<div id="template-index">
<div class="row">
<div class="col-sm-12">
<div class="info-box">
<div class="info-box-title">
Templates
</div>
<div class="info-box-content" ng-controller="ConnectAdmin.Controllers.TemplateIndexController as templateCtrl">
<table class="table table-striped table-responsive">
<thead>
<tr>
<td>#</td>
<td>Name</td>
<td>Description</td>
</tr>
</thead>
<tbody>
<tr class="tr-select" ng-click="templateCtrl.openTemplate(template.templateId)" ng-repeat="template in templateCtrl.templates.collection">
<td>{{template.templateId}}</td>
<td>{{template.name}}</td>
<td>{{template.description}}</td>
</tr>
</tbody>
</table>
<div id="template-index-loader" class="loader" ng-show="templateCtrl.processing"></div>
<div class="info-box-footnote" ng-hide="templateCtrl.templates.collection.length">
Displaying {{templateCtrl.templates.skipped + 1}} to {{templateCtrl.templates.set + templateCtrl.templates.skipped}} of {{templateCtrl.templates.total}}
</div>
<div class="info-box-footnote" ng-show="templateCtrl.message.length">
{{templateCtrl.message}}
</div>
</div>
</div>
</div>
</div>
I don't think its the http call as I get no update if I return a hardcoded object.
The alert in the success callback gives me a correct value.
Thanks
My hunch is that your scope is being changed in your success callback. Try using your controller scope you defined in your constructor like this
successCallback(data: TemplateCollection) {
store.templates = { skipped: 0, set: 0, total: 0, collection: [] }
store.templates = data;
alert(store.templates.collection.length);
}
Otherwise I think when you say, "this" you're referring to the scope of the successCallback function
Ah great! Thanks, you put me on the right track.
Doing the update you said I was getting intellisense promts to say do you mean this.store which had the same outcome.
Following on from that and doing a bit of digging yes all the variables were undefined.
I've updated the Controller and Service to be:
module ConnectAdmin.Controllers {
import TemplateCollection = Interfaces.ITemplateCollection;
export interface ITemplateIndexScope extends ng.IScope {
vm: any;
}
export class TemplateIndexController {
static $inject = ["ConnectAdmin.Services.TemplateService"];
constructor(templateService: ConnectAdmin.Services.TemplateService) {
this.templates = { skipped: 0, set: 0, total: 0, collection: [] };
this.templateService = templateService;
this.take = 20;
this.skip = 0;
this.refresh();
}
refresh() {
this.processing = true;
this.templateService.index(this.take, this.skip, this);
}
successCallback(data: TemplateCollection) {
this.templates = data;
alert(this.templates.collection.length);
this.processing = false;
}
errorCallback(response: any) {
this.templates = { skipped: 0, set: 0, total: 0, collection: [] };
alert(response.status);
this.message = "An Error Occurred Contacting the API";
this.processing = false;
}
processing: boolean;
templates: TemplateCollection;
take: number;
skip: number;
message: string;
templateService: Services.TemplateService;
}
angular.module("ConnectAdmin").controller("ConnectAdmin.Controllers.TemplateIndexController", TemplateIndexController);
}
module ConnectAdmin.Services {
import TemplateCollection = Interfaces.ITemplateCollection;
import TemplateIndexController = Controllers.TemplateIndexController;
export class TemplateService {
constructor($http: ng.IHttpService) {
this.http = $http;
}
http: ng.IHttpService;
index(take: number, skip: number, templateController: TemplateIndexController) {
const req = {
method: "GET",
url: "https://localhost:44336/api/Templates?take=" + take + "&skip=" + skip,
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
};
this.http(req).then(response => {
var data = response.data as TemplateCollection;
templateController.successCallback(data);
},
response => {
templateController.errorCallback(response);
});
}
}
angular.module("ConnectAdmin").service("ConnectAdmin.Services.TemplateService", TemplateService);
}
So I'm passing the instance of the controller into the service rather than the callback functions.
Cheers

Angular with Coffeescript: why my method are executed?

I'm an angular beginner, and coming from Ruby I choose to use Coffescript instead of JS. I'm using ng-classify to define my controller, services and Factory with Coffeescript classes, but I cannot understand what is wrong.
I have my code in this [github repo], but I try to explain here my issue.
I have this controller
class Setting extends Controller
constructor: (#DataService,$log) ->
#examType = #DataService.getObject('setting_examtype') || { checked: false }
#settingList = #DataService.getObject('setting_list') || [
{ text: 'Dai precedenza a domande sbagliate', checked: false },
{ text: 'Dai precedenza a domande mai fatte', checked: false },
{ text: 'Mostra subito la soluzione', checked: false }
]
#questionPossibility = [10,20,30,40,50]
#questionNumber = #DataService.get('question_number') || 30
return
examTypeChecked: () =>
#DataService.setObject('setting_examtype',#examType)
console.log 'examTypeChecked'
return
settingListChecked: () =>
console.log 'settingListChecked'
#DataService.setObject('setting_list',#settingList)
return
questionNumberChecked: () =>
console.log 'questionNumberChecked'
#DataService.set('question_number',#questionNumber)
return
The compiled version is:
(function() {
var Setting,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
Setting = (function() {
function Setting(DataService, $log) {
this.DataService = DataService;
this.questionNumberChecked = __bind(this.questionNumberChecked, this);
this.settingListChecked = __bind(this.settingListChecked, this);
this.examTypeChecked = __bind(this.examTypeChecked, this);
this.examType = this.DataService.getObject('setting_examtype') || {
checked: false
};
this.settingList = this.DataService.getObject('setting_list') || [
{
text: 'Dai precedenza a domande sbagliate',
checked: false
}, {
text: 'Dai precedenza a domande mai fatte',
checked: false
}, {
text: 'Mostra subito la soluzione',
checked: false
}
];
this.questionPossibility = [10, 20, 30, 40, 50];
this.questionNumber = this.DataService.get('question_number') || 30;
return;
}
Setting.prototype.examTypeChecked = function() {
this.DataService.setObject('setting_examtype', this.examType);
console.log('examTypeChecked');
};
Setting.prototype.settingListChecked = function() {
console.log('settingListChecked');
this.DataService.setObject('setting_list', this.settingList);
};
Setting.prototype.questionNumberChecked = function() {
console.log('questionNumberChecked');
this.DataService.set('question_number', this.questionNumber);
};
return Setting;
})();
angular.module('app').controller('settingController', ['DataService', '$log', Setting]);
}).call(this);
As you can see I insert some log statement, and from the console I understand that all my methods are executed. Why? Why examTypeChecked is called?
I call it only if someone use a toggle..
<ion-toggle ng-model="setting.examType" ng-checked="setting.examTypeChecked()" toggle-class="toggle-calm" ng-true-value="oltre" ng-false-value="entro">Tipo di esame</ion-toggle>
You got it wrong way, your code is fine, use of code is not what you expected
<ion-toggle ng-model="setting.examType" ng-checked="setting.examTypeChecked()" toggle-class="toggle-calm" ng-true-value="oltre" ng-false-value="entro">Tipo di esame</ion-toggle>
setting.examTypeChecked() will be called every time $digest() process is triggered, and it's triggered with each change of model, by $scope.apply(), $scope.digest(), $timeout() and few more

Resources