AngularJS module.factory get remote json - json

I work on PhoneGap with AngularJS I need some help to get data from remote JSON server. How can I do that in module factory?
My JSON file:
[
{
'name':'',
'number:'',
'department':''
}
]
And my JavaScript:
(function(){
use strict';
var module = angular.module('app', ['onsen']);
module.controller('AppController', function($scope, $data) {
$scope.doSomething = function() {
setTimeout(function() {
ons.notification.alert({ message: 'tapped' });
}, 100);
};
});
module.controller('DetailController', function($scope, $data) {
$scope.item = $data.selectedItem;
});
module.controller('MasterController', function($scope, $data) {
$scope.items = $data.items;
$scope.showDetail = function(index) {
var selectedItem = $data.items[index];
$data.selectedItem = selectedItem;
$scope.navi.pushPage('detail.html', {title : selectedItem.title});
};
});
module.factory('$data', function() {
var data = {};
data.items = [
{
title: 'Noor almosswi',
label: '',
desc: 'Working in Managment',
phone: '0000',
photo:'http://cdn2.hubspot.net/hub/63072/file-14997515-jpg/images/jeremywilcomb_thedanielgroup.jpg?t=1430422772606&width=229&height=229'
},
{
title: 'Safe khalid',
label: '',
desc: 'Working in accounting',
phone: '00000',
photo:'http://localhost/workflow/photos/c0d179d424ae9c327609c5d80e94c6e0_thumb.jpg'
},
{
title: 'Yussif ali',
label: '',
desc: 'Working in Development',
phone: '0000',
photo:'http://www.beyondcareersuccess.com/wp-content/uploads/2012/08/employee.png'
},
{
title: 'Ali kreeam',
label: '',
desc: 'Working in call center',
phone: '000000',
photo:'http://www.piranhaphotography.com/blog/wp-content/uploads/2010/05/brookfield-employee-portrait-photograph-0366.jpg'
}
];
return data;
});
})();

in your factory you can just use
$http.get('url').then(function(data){});
make sure you inject $http as well

Related

How to show antd multiple select component on this Simple Schema

I have this JSON schema, I tried to populate multiple select component with the uniform autoform.
(() => {
const ajv = new Ajv({ allErrors: true, useDefaults: true, keywords: ["uniforms"] });
const schema = {
title: 'Address',
type: 'object',
properties: {
city: {
type: 'string',
uniforms: {
options: [
{ label: 'New York', value: 'new york' },
{ label: 'Nashville', value: 'nashville' },
],
},
},
}
};
function createValidator(schema) {
const validator = ajv.compile(schema);
return (model) => {
validator(model);
if (validator.errors && validator.errors.length) {
return { details: validator.errors };
}
};
}
const schemaValidator = createValidator(schema);
return new JSONSchemaBridge(schema, schemaValidator);
})()
And the result look like this
Rendered component with this JSON schema
The multiselect component example from antd
could I render multiselect component instead select component (which default from uniform)?
Can I select new york and nashville at the same time?

Vue. Js Laravel count elements of JSON

I would like to display the number of tasks elements in JSON, but I do not know how to go about it.
I want to make something like this:
Tasks to do 2/12 (where 2 - tasks with flag 1, 12 - all tasks)
I tried using the lenght function, but I got the information function lenght is not defined, similarly with the slice function.
[
{
"id":1,
"clients_id":1,
"products_id":1,
"tasks_id":1,
"project_name":"Some project",
"created_at":null,
"updated_at":null,
"clients":{
"id":1,
"client_name":"Some client",
"contact_name":"Some client",
"client_phone":"123123123",
"client_mail":"clientmail#mailclient.com",
"client_nip":"1112223333",
"client_logo":"logo.jpg",
"updated_at":"2019-04-11 09:45:11",
"created_at":"-0001-11-30 00:00:00"
},
"products":{
"id":1,
"product_name":"Some product",
"product_description":"Really nice product bro",
"product_price":"999$",
"updated_at":"2019-04-08 14:35:13",
"created_at":null
},
"tasks":[
{
"id":1,
"project_id":1,
"task_name":"First task",
"task_description":"its very hard task",
"task_due":"2099-01-12 00:00:00",
"status":0,
"created_at":null,
"updated_at":"2019-04-11 14:09:08"
},
{
"id":2,
"project_id":1,
"task_name":"fix task 1",
"task_description":"or something else",
"task_due":"2201-01-12 00:00:00",
"status":1,
"created_at":null,
"updated_at":"2019-04-11 14:10:11"
}
]
}]
<script>
export default {
mounted() {
let app = this;
let id = app.$route.params.id;
app.id = id;
axios.get('/api/v1/projects/' + id)
.then(function (resp) {
app.project = resp.data;
})
.catch(function () {
alert("Could not load your projects")
});
},
data: function () {
return {
//client_id: null,
project: {
id: '',
clients_id: '',
products_id: '',
tasks_id: '',
project_name: '',
updated_at: '',
created_at: '',
clients: ''
},
task: {
status: ''
}
//client: []
}
},
methods: {
saveForm() {
var app = this;
var newproject = app.project;
axios.patch('/api/v1/projects/' + app.id, newproject)
.then(function (resp) {
app.$router.replace('/c/');
})
.catch(function (resp) {
console.log(resp);
alert("Could not create your company");
});
},
taskDone(taskid, projectid){
var app = this;
{{app}};
var newtask = app.task;
var flag = 1;
axios.patch('/api/v1/tasks/' + taskid + '?status='+flag)
.then(function (resp) {
app.$router.push('/pr/view/' + projectid);
location.reload();
})
.catch(function (resp) {
console.log(resp);
alert("Could not create your company");
});
},
taskUnDone(taskid, projectid){
var app = this;
{{app}};
var newtask = app.task;
var flag = 0;
axios.patch('/api/v1/tasks/' + taskid + '?status='+flag)
.then(function (resp) {
app.$router.push('/pr/view/' + projectid);
location.reload();
})
.catch(function (resp) {
console.log(resp);
alert("Could not create your company");
});
}
}
}
</script>
You could create a computed function that returns the length of tasks filtered by status of 1.
computed() {
status() {
const tasks = this.project.tasks;
const complete = tasks.filter(task => task.status === 1);
return `${complete.length}/${tasks.length}`;
}
}
Then use status as a "variable" in your markup.
<p>Tasks done: {{ status }}</p>

How to show reactive map at meteor/autoform, and get marker full adress

So i've been struggling for a week to make this happen!!!!
In short, my structure is as follows :
Address = new SimpleSchema({
location: {
type: Object
},
fullAddress: {
type: String
},
country: {
type: String
},
governorate: {
type: String
},
city: {
type: String
},
street: {
type: String
},
building: {
type: Number
}
});
Branch = new SimpleSchema({
address: {
type: Address
},
....
});
Companies = new Mongo.Collection('companies');
CompanySchema = new SimpleSchema({
branch: {
type: [Branch],
minCount: 1
},
....
});
Companies.attachSchema(CompanySchema);
As you can see, I have an array of branches, with all branch has an address & location.
I want to be able to show a map for each [Branch]/Address when calling autoform like:
{{> quickForm collection="Companies" type="insert" id="company_form"}}
Then, have some map click listener to place a marker, and then reverse geoDecode location to populate the address fields
I have tried following yogiben:autoform-map, but the package is incomplete (has MyLocation button issues zoom exceptions, and cannot show multiple maps per page) thus, cannot be used in production.
I am disparate...Please help!
So, I created my own solution, and I'll share it to benefit any one having the same issue.
I modified yogiben/meteor-autoform-map and added a pull request adding geoCoding feature along with a lot of other stuff.
The following is my current autoform configurations & handling:-
Schema
Location = new SimpleSchema({
location: {
type: Object,
autoform:{
type: 'map',
label: false,
afFieldInput: {
mapType: 'terrain',
defaultLat: 30.0444196,
defaultLng: 31.23571160000006,
geolocation: true,
autolocate: true,
searchBox: true,
language: function(){ return getUserLanguage(); },
direction: function(){ return (getUserLanguage() == 'ar')? 'rtl' : 'ltr'; },
zoom: 16,
key: Meteor.settings.public.google_maps_key,
googleMap: {
mapTypeControl: false
},
geoCoding: true,
geoCodingCallBack: 'reverseGeoCode',
animateMarker: true
}
}
},
placeId: {
type: String,
autoform: {
type: 'hidden'
},
autoValue: function(){
return '';
}
},
createdAt: {
type: Date,
autoValue: function(){
return new Date();
},
autoform: {
type: 'hidden'
}
}
});
Address = new SimpleSchema({
location: {
type: Location,
label: function(){
return (Session.get('lang') == 'ar')? 'الموقع على الخريطة' : 'Map Location';
}
},
country: {
type: String,
label: function(){
return (Session.get('lang') == 'ar')? 'الدولة' : 'Country';
},
autoform: {
afFieldInput: {
placeholder: function(){
return (Session.get('lang') == 'ar')? 'الدولة' : 'Country';
}
},
type: 'hidden'
}
},
governorate: {
type: String,
label: function(){
return (Session.get('lang') == 'ar')? 'المحافطة' : 'Governorate';
},
autoform: {
afFieldInput: {
placeholder: function(){
return (Session.get('lang') == 'ar')? 'المحافظة' : 'Governorate';
}
}
}
},
city: {
type: String,
label: function(){
return (Session.get('lang') == 'ar')? 'المدينة' : 'City';
},
autoform: {
afFieldInput: {
placeholder: function(){
return (Session.get('lang') == 'ar')? 'المدينة' : 'City';
}
}
}
},
district: {
type: String,
label: function(){
return (Session.get('lang') == 'ar')? 'الحي' : 'District';
},
autoform: {
afFieldInput: {
placeholder: function(){
return (Session.get('lang') == 'ar')? 'الحي' : 'District';
}
}
}
},
street: {
type: String,
label: function(){
return (Session.get('lang') == 'ar')? 'الشارع' : 'Street';
},
autoform: {
afFieldInput: {
placeholder: function(){
return (Session.get('lang') == 'ar')? 'اسم \ رقم الشارع' : 'Street Name / Number';
}
}
}
},
building: {
type: String,
label: function(){
return (Session.get('lang') == 'ar')? 'رقم المبنى' : 'Building Number';
},
regEx: /[\d+\-]/,
autoform: {
afFieldInput: {
placeholder: function(){
return (Session.get('lang') == 'ar')? 'رقم المبنى' : 'Building Number';
}
},
}
},
createdAt: {
type: Date,
autoValue: function(){
return new Date();
},
autoform: {
type: 'hidden'
}
}
});
Branch = new SimpleSchema({
name: {
type: String,
label: function(){
return (Session.get('lang') == 'ar')? 'اسم الفرع' : 'Branch Name';
},
autoform: {
afFieldInput: {
placeholder: function(){
return (Session.get('lang') == 'ar')? 'اسم الفرع' : 'Branch Name';
}
}
}
},
address: {
type: Address,
label: function(){
return (Session.get('lang') == 'ar')? 'العنوان' : 'Address';
},
minCount: 1,
optional: false
},
createdAt: {
type: Date,
autoValue: function(){
return new Date();
},
autoform: {
type: 'hidden'
}
}
});
CompaniesSchema = new SimpleSchema({
name: {
type: String,
label: function(){
return (Session.get('lang') == 'ar')? 'اسم الشركة' : 'Company Name';
},
autoform: {
afFieldInput: {
placeholder: function(){
return (Session.get('lang') == 'ar')? 'اسم الشركة' : 'Company Name';
}
}
}
},
branches: {
type: [Branch],
label: function(){
return (Session.get('lang') == 'ar')? 'الفرع' : 'Branch';
}
},
createdAt: {
type: Date,
autoValue: function(){
return new Date();
},
autoform: {
type: 'hidden'
}
}
});
client/main.js
Meteor.startup(() => {
// ================================================================ //
// Functions that need to be global perior to Packages loading //
// ================================================================ //
// Get Initial/Current user language
getUserLanguage = function () {
return Session.get('lang') || Meteor.settings.public.defaultLang;
};
// Reverse Geocode location
// #param t => Template Instance - object
// #param geocoder => google.map.geocoder - object
// #param location => google.maps.LatLng - object
reverseGeoCode = function(t, geocoder, location){
var latlng = {lat: location.lat(), lng: location.lng()};
var geoCodingOpt = {
'location' : latlng,
'language' : Session.get('lang'),
'region' : 'eg'
};
geocoder.geocode(geoCodingOpt, function(results, status){
if(status === 'OK'){
if(results.length !== 0){
var address = results[0];
var cmp = address.address_components;
var pfx = t.data.name.replace(/.location/g,'');
var sel = '[name="' + pfx + '.' + 'xx' + '"]';
var selObj = {
placeId : sel.replace('xx', 'location.placeId'),
country : sel.replace('xx', 'country'),
governorate : sel.replace('xx', 'governorate'),
city : sel.replace('xx', 'city'),
district : sel.replace('xx', 'district'),
street : sel.replace('xx', 'street'),
building : sel.replace('xx', 'building')
};
// Address Container DOM element
$addressElm = $(t.firstNode.closest('.autoform-array-item'));
// Place ID
$addressElm.find(selObj.placeId).val(address.place_id);
// Country
$addressElm.find(selObj.country).val(cmp[5].long_name);
// Governorate
$addressElm.find(selObj.governorate).val(cmp[4].long_name);
// City
$addressElm.find(selObj.city).val(cmp[3].long_name);
// District
$addressElm.find(selObj.district).val(cmp[2].long_name);
// Street
$addressElm.find(selObj.street).val(cmp[1].long_name);
// Building
$addressElm.find(selObj.building).val(cmp[0].long_name);
// Clear DOM refference for Garbage Collection
$addressElm.prevObject = null;
$addressElm = null;
}
}
});
}
});
Hope that helps anyone.
Feel free to inquire any elaborations

passsing data to https by JSON using JSONP

i had try many diffrent tutarials and examples from http://api.jquery.com/jQuery.getJSON/ and Post data to JsonP and saw many staffs about how to convert json data to jasonP but still i can not do it,is there any one could see how should i pass my data over https within my codes here which i am using highcharts to get data from my domain sql server which is in diffrent server than my webpages host.here is my codes:(i know which i should use ajax request but i dont know how in my case,if anyone know please HELP!) tnx.
getting data by getJASON over data.php which request from sql server to grab data:
var Options;
$(document).ready(function() {
Options = {
chart: {
renderTo: 'container2',
type: 'area',
borderColor: "#3366ff",
borderWidth:5,
zoomType : 'x'
},
title: {
text: 'Total Meeting_Logs Duration of Organization1 '
},
subtitle: {
text: ' '
},
credits:{
enabled:false
},
xAxis: {
categories: [],
labels: {
align: 'center',
x: -3,
y: 20,
//format data based on #datepicker which is html jquery ui date
//picker
formatter: function() {
return Highcharts.dateFormat('%l%p',
Date.parse(this.value +' UTC'));
}
}
},
yAxis: {
title: {
text: ''
}
},
tooltip: {
backgroundColor: '#FCFFC5',
borderColor: 'black',
borderRadius: 10,
borderWidth: 3
},
// Enable for both axes
tooltip: {
crosshairs: [true,true]
},
plotOptions: {
line: {
dataLabels: {
enabled: true
},
enableMouseTracking: false
}
},
series: [{
type: 'area',
name: '',
data: []
}]
}
// here i get my data from data.php within same server
$.getJSON("data.php", function(json){
Options.xAxis.categories = json['category'];
Options.series[0].name = json['name'];
Options.series[0].data = json['data'];
chart = new Highcharts.Chart(Options);
});
});
//this function get user request for input time period and
//update in my domain
$(function() {
$( "#datepicker2" ).datepicker({
dateFormat: "yy-mm-dd",
showOn: "button",
buttonImage: "calendar.gif",
buttonImageOnly: true,
onSelect: function(dateText, inst) {
$.getJSON("data.php?dateparam1="+dateText, function(json){
Options.xAxis.categories = json['category'];
Options.series[0].name = json['name'];
Options.series[0].data = json['data'];
chart = new Highcharts.Chart(Options);
});
}
});
});
data.php:
`
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("moh1368_Mrs_Lemoine", $con);
if (isset($_GET["dateparam"])) {
$sql = mysql_query("SELECT timestamp_value, traffic_count FROM
foot_traffic WHERE timestamp_value LIKE '".$_GET["dateparam"]."%'");
} else {
$sql = mysql_query("SELECT timestamp_value, traffic_count FROM
foot_traffic WHERE timestamp_value LIKE '2013-02-01%'");
}
$result['name'] = 'Foot Traffic Count';
while($r = mysql_fetch_array($sql)) {
$datetime = $r['timestamp_value'];
$result['category'][] = $datetime;
$result['data'][] = $r['traffic_count'];
}
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>`

BackboneJS - this.collection is undefined

i have this Backbone View:
define(['backbone','handlebars', 'text!templates/AlphabetList.html'],
function(Backbone,Handlebars, Template) {
'use strict';
var View = Backbone.View.extend({
template: Handlebars.compile(Template),
events: {
'click li':'li_clickHandler'
},
li_clickHandler: function(e) {
var id = $(e.currentTarget).attr('data-id');
Backbone.history.navigate('/category/'+id, {trigger:true});
},
initialize: function () {
},
render: function() {
$(this.el).html(this.template({menu:this.collection.toJSON()}));
return this;
}
});
return View;
}
);
here is my router:
define([
'backbone',
//Views
'views/ArtistTopImage',
'views/AlphabetList',
'collections/AlphabetCollection',
],
function(
Backbone,
AlphabetList,
ArtistTopImage,
AlphabetCollection
) {
'use strict';
var ArtistRouter = Backbone.Router.extend({
routes: {
'': 'index'
},
//Initializing the application
initialize: function () {
var self = this;
//Collections
this.AlphabetCollection = new AlphabetCollection({catId:0});
//Views
this.artistTopImageView = new ArtistTopImage({el:'.ti'});
this.AlphabetList = new AlphabetList({el:'#alphabetical', collection:this.AlphabetCollection});
self.artistTopImageView.render();
this.AlphabetCollection.fetch({success: function(collection) {
self.AlphabetList.collection=collection;
self.AlphabetList.render();
}});
Backbone.history.start({
pushState: false
});
},
//Default route.
index: function () {
var self = this;
},
});
return ArtistRouter;
}
);
And here is my Collection:
define([
"backbone",
"models/AlphabetModel"
],
function(Backbone, AlphabetModel) {
var AlphabetCollection = Backbone.Collection.extend({
model: AlphabetModel,
catId: null,
initialize: function(attrs) {
this.catId=attrs.catId;
},
url: function() {
return "Alphabetical"+this.catId+".json";
}
});
return AlphabetCollection;
});
The HTML template
<ol class="alist">
{{#each menu}}
<li data-id="{{this.url}}">{{this.name}}</li>
{{/each}}
</ol>
and the JSON file:
[
{
"name":"0-9",
"id":"1",
"url":"0"
},
{
"name":"A",
"id":"2",
"url":"1"
},
{
"name":"B",
"id":"3",
"url":"2"
},
{
"name":"C",
"id":"4",
"url":"3"
},
{
"name":"D",
"id":"5",
"url":"4"
}
]
this gives me an error: "this.collection is undefined". I dont know what the problem is, so does someone have an idea?