How to load more than one json file in angular - json

I am wondering how to load multiple .json files in to template.
In my example I have submissions from users and I do not want to store everything in one json file if possible.
How to grab some data from multiple json files?
here is my plunk example
I want to load users.json as well
var app = angular.module('myApp', []);
app.directive('contentItem', function ($compile,$parse) {
templates = {
image: 'image.html',
event: 'event.html',
article: 'article.html',
ad: 'ad.html',
discount: 'discount.html',
video: 'video.html'
}
var linker = function(scope, element, attrs) {
scope.setUrl = function(){
return templates[scope.content.content_type];
}
}
return {
restrict: "E",
replace: true,
link: linker,
scope: {
content: '='
},
templateUrl: 'main.html'
};
});
function ContentCtrl($scope, $http) {
"use strict";
$scope.url = 'content.json';
$scope.content = [];
$scope.fetchContent = function() {
$http.get($scope.url).then(function(result){
$scope.content = result.data;
});
}
$scope.fetchContent();
}
Help appreciated

You can request for JSON either from the controller like:
app.controller('myController', function($scope, $http){
$scope.users = [];
$scope.getUsers = function() {
$http({method: 'JSONP', url: "users.json?query=?callback=JSON_CALLBACK&query="+ $scope.searchString}).
success(function(data, status) {
$scope.users = data;
}).
error(function(data, status) {
console.log(data || "Request failed");
});
};
and the other approach (better one) would be to make use of angular factory to fetch the JSON file.
myApp.factory('getUsersFactory',['$http',function($http){
return {
getUsers: function(callback){
$http({method: 'JSONP', url: "users.json?query=?callback=JSON_CALLBACK&query="+ $scope.searchString}).success(callback);
}
}
}]);
where now you can include this factory as a dependency and get the user data and assign that in the callback function.

Related

retrieve json data using GET in angularjs

I've got some data stored in a nosql database that I'm able to see in when accessing localhost:3000/countries.
I'm trying to use this factory in order to get the data which is in json.
.factory('countries', ['$http', '$q',
function($http, $q) {
var countries = {
get: function() {
return $q(function(resolve, reject) {
$http({
method: 'GET',
url: '/countries'
}).then(function(response) {
resolve(response.data);
}, function(error) {
reject(error);
});
});
};
return countries;
}
]);
And then I'm attempting to use this controller to send that data to the appropriate url to be displayed but it isn't working as I expected it to.
.controller('CountriesCtrl', function($scope, countries) {
console.log(countries);
countries.get(function(countries) {
$scope.countries = countries;
});
})
Any thoughts or suggestions? Thanks!
This is what I use currently in my project that uses Mongodb
cmsApp.factory("tasks", ["$resource", function($resource) {
return $resource("/tasks/", {}, {
save: {
method: 'POST',
isArray: true
},
'delete': {
method: 'DELETE',
isArray: true
}
});
}]);
Then in the Controller(make sure to inject it to controller!):
$scope.tasks = tasks.query();
.query() selects all of the data while .get() gets on by Id
You should inject your factory into your controller, something like this:
.controller('CountriesCtrl', function($scope, devices) {
console.log(countries);
countries.get(function(data) {
$scope.data = data;
});
})
You should inject service 'devices' instead of it's internal variable 'countries'.
.controller('CountriesCtrl', function($scope, devices) {
console.log(devices);
devices.get().then(function(countries) {
$scope.countries = countries;
});
});

AngularJS : Factory JSON Array with HTTP GET

I'm developing my first AngularJS app using the Google Docs API to pass it JSON data.
This is an example of the factory I'm using:
app.factory('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
return {
news:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/1/public/values?alt=json', {cache: true});
},
updates:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/2/public/values?alt=json', {cache: true});
},
docs:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/3/public/values?alt=json', {cache: true});
}
}]);
I wanted to clean up a bit the code and decided to use services instead of making the calls in the controller itself. It works normally, but it's a pain in the ass the fact that I still need to write long $scopes because of the structure of the Google API. This is how I get the values in the controller:
app.controller('homeCt', ['$scope', 'Data', function ($scope, Data){
Data.news().success(function (data) {
$scope.totalNews = data.feed.entry.length;
});
}]);
Is there a way that I can set the factory service to pass me the data just using:
$scope.totalNews = Data.news()
Or at least removing the 'feed.entry'?
Data.news().success(function (data) {
$scope.totalNews = data.length;
});
Thank you very much!
example of service - resolve the success with the data you want
app.service('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
this.news =function(){
return $http.get(googleDocs + apiKeys.googleDoc +'/1/public/values? alt=json', {cache: true})
.then(function(data){
return data.feed.entry.length;
});
}
}]);
the controller - since you already resolved the data in service hence..
app.controller('homeCt', ['$scope', 'Data', function ($scope, Data){
Data.news().then(function (data) {
$scope.totalNews = data;
});
}]);
working example
var app = angular.module('app', ['ionic'])
.service('Data', ['$http',
function($http) {
var googleDocs = 'https://spreadsheets.google.com/feeds/list/1aC1lUSxKatfxMKEy1erKDSAKgijSWOh77FDvKWhpwfg/1/public/values?alt=json';
this.news = function() {
return $http.get(googleDocs, {
cache: true
}).then(function(res) {
return res.data.feed.entry;
});
}
}
])
.controller('homeCt', ['$scope', 'Data',
function($scope, Data) {
Data.news().then(function(data) {
console.log(data);
})
}
]);
I'll give you a way of doing it, a way that I don't recommend at all (a service should not handle the scope), but for me it is the only way you have if you don't want to destroy the "async" of your ajax call :
app.factory('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
return {
news:news,
updates: updates,
[...]
}
function news(scopeValue) {
$http.get(googleDocs + apiKeys.googleDoc +'/1/public/values?alt=json', {cache: true}).success(function(data){
scopeValue = data;
});
}]);
and then, call it that way in your controller :
Data.news($scope.totalNews);

angularJS add JSON by http request

want to download a JSON of beercat('bieres.json') in this.bieres
How could I do?
function() {
var app = angular.module('monStore', []);
app.service('dataService', function($http) {
this.getData = function() {
return $http({
method: 'GET',
url: 'bieres.json'
});
}
});
app.controller('StoreController', function($scope,dataService){
this.bieres = [];
dataService.getData().then(function(dataResponse) {
$scope.bieres = dataResponse.data;
});
...
});
I think it's my access by this.bieres that it's wrong,
the Json is loaded in the console, but a blank page is in result

How to render jsonp fetched in BackboneJS?

I'm new in BackboneJS, and I can't render information from JSONP. If I put the data into a data.json and I fetch it, the count appears in the console, but when I use JSONP never re-render.
I don't know if is some kind of delay for obtain the data, but the event of "change" and "reset" are not being trigged by the collection to re-render the view.
The code I have is the next:
// Collection
define([
'underscore',
'backbone',
'models/EstablecimientoModel'],function(_, Backbone, EstablecimientoModel){
var EstablecimientoCollection = Backbone.Collection.extend({
model: EstablecimientoModel,
initialize: function(models, options) {
console.log("Establecimiento initialize");
},
url: function() {
return '../js/establecimientos.json';
//return 'http://localhost:3000/establecimiento';
},
parse: function(data) {
console.log("End of loading data " + JSON.stringify(data) + " datos");
return data;
},
});
return EstablecimientoCollection;
});
// Router
define([
'jquery',
'underscore',
'backbone',
'views/establecimiento/EstablecimientoView',
'jqm'
], function($, _, Backbone,EstablecimientoView) {
'use strict';
var Router = Backbone.Router.extend({
//definition of routes
routes: {
'nearMe' : 'nearMe',
},
nearMe: function(actions) {
var estaColl = new EstablecimientoCollection();
var establecimientoView = new EstablecimientoView({ collection: estaColl });
//estaColl.fetch();
//establecimientoView.render();
this.changePage(establecimientoView);
},
init: true,
changePage: function(view) {
//add the attribute data-role="page" for each view's div
$(view.el).attr('data-role','page');
view.render();
// append to the DOM
$('body').append($(view.el));
var transition = $.mobile.defaultPageTransition;
if(this.firstPage) {
transition = 'none';
this.firstPage = false;
}
// Remove page from DOM when it’s being replaced
$('div[data-role="page"]').on('pagehide', function (event, ui) {
$(this).remove();
});
$.mobile.changePage($(view.el), { transition: transition, changeHash: false });
} // end of changePage()
});
return Router;
});
// View
define([
'jquery',
'underscore',
'backbone',
'collections/EstablecimientoCollection',
'text!templates/establecimiento/establecimientoTemplate.html'
],function($, _, Backbone, EstablecimientoCollection, establecimientoTemplate) {
var EstablecimientoView = Backbone.View.extend({
initialize: function() {
var self = this;
_.bindAll(this,"render");
this.collection.on("change",self.render);
this.collection.fetch({ dataType: 'jsonp', success: function(){ self.render() }});
}, //end of initialize()
template: _.template(establecimientoTemplate),
render: function(eventName) {
console.log("render");
console.log(this.collection.length);
return this;
}, //end of render()
});
return EstablecimientoView;
});
When you fetch your data, make sure you're setting the dataType for your fetch call. Fetch is wrapping a jQuery/Zepto ajax call, so you'll need to set the same parameters you would with those.
this.collection.fetch({
reset: true,
dataType: 'jsonp',
success: function () {
// do stuff
}
});
Also, I'd have your view listen for the events published by the collection rather than calling the view's render directly from the fetch's success callback.

AngularJS 1.2.7 IE8 resource bug

Sample code available here & here. Since Plunker doesn't support IE8 or IE9 very well, the example code can be run by opening the Plunker example in a modern web browser and then launching the Run pane in a separate window and opening that URL in IE8 or IE9.
When making a RESTful call using $resource.query or $resource.get, the promise fails to return any results on IE8 or IE9 if a custom action is defined and used:
factory('ResourceService2', ['$resource', '$q', function($resource, $q) {
var factory = {
query: function() {
var deferred = $q.defer();
$resource('data.json', {'cacheSlayer' : new Date().getTime()}, {
'query': {
method: 'GET',
responseType: 'json',
isArray: true
}}).query(function (data) {
deferred.resolve(data);
});
return deferred.promise;
}
};
return factory;
}]).
query():
ResourceService2.query().then(function (response) {
$scope.resource2Rows = response;
});
However, this same call successfully returns results when a custom action is not defined or used:
factory('ResourceService', ['$resource', '$q', function($resource, $q) {
var factory = {
query: function() {
var deferred = $q.defer();
$resource('data.json', {
'cacheSlayer' : new Date().getTime()
}, {}).query(function (data) {
deferred.resolve(data);
});
return deferred.promise;
}
};
return factory;
}]).
query():
ResourceService.query().then(function (response) {
$scope.resourceRows = response;
});
Using $http is also successful:
factory('HttpService', ['$http', '$q', function($http, $q) {
var factory = {
query: function() {
var deferred = $q.defer();
$http.get('data.json', {
params: {
'cacheSlayer' : new Date().getTime()
}}).success(function (data) {
deferred.resolve(data);
});
return deferred.promise;
}
};
return factory;
}]).
get():
HttpService.query().then(function (response) {
$scope.httpRows = response;
});
Is this a bug in IE8/IE9? What additional parameters for a custom action must be defined for IE8/IE9 compatibility? The Angular Developer's Guide makes no mention of this problem as of 1.2.7.
CORS is not implemented fully in ie8/9 so this is most likely your issue. Here is the msdn article about it:
http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx