Error: dailyData[i] is undefined angularjs - javascript

I have problem with my code. Actually, when i run the application then i get message like dailyData[i] is undefined and I am getting the form as 'undefined'.
This is my code:
(function() {
var app = angular.module('starter.isu', ['ionic','ngCordova','ngMaterial']);
app.controller('isuctrl', function($scope, $http) {
var service_url = "https:code=isu";
$http.get(service_url)
.success(
function(data) {
console.log(data);
dailyData =data.result.response.airport.pluginData.schedule.arrivals.data;
$scope.dailyForecast = [];
for(var i=0; i<25; i++)
{
$scope.dailyForecast[i] = {
callsign: dailyData[i].flight.identification.number.default,
statu: dailyData[i].flight.status.generic.status.text,
airline: dailyData[i].flight.airline.code.icao,
from: dailyData[i].flight.airport.origin.position.region.city,
timear: dailyData[i].flight.time.scheduled.arrival,
generic: dailyData[i].flight.status.text,
};
}
})
})
})();

Related

Angular JS / articles is not defined

I have this code in services.js in in my Angular App:
.factory('Articles', function($http) {
$http.get('https://api.myjson.com/bins/4ici6').then( function(response) {
var articles = response.data.articles;
});
return {
all: function() {
return articles;
},
get: function(articleId) {
for (var i = 0; i < articles.length; i++) {
if (articles[i].id === parseInt(articleId)) {
return articles[i];
}
}
return null;
}
};
})
It doesn't work as I get this error in the console:
ReferenceError: articles is not defined
at Object.all (http://localhost:8100/js/services.js:31:14)
at new <anonymous> (http://localhost:8100/js/controllers.js:4:30)
at Object.instantiate (http://localhost:8100/lib/ionic/js/ionic.bundle.js:18015:14)
Also here is the controller.js code that refers to articles:
.controller('NewsCtrl', function($scope, Articles) {
$scope.articles = Articles.all();
})
.controller('NewsDetailCtrl', function($scope, $stateParams, Articles) {
$scope.article = Articles.get($stateParams.articleId);
$scope.posttofacebook = function (){
window.plugins.socialsharing.shareViaFacebook(null, null, $scope.article.url);
}
$scope.posttotwitter = function (){
window.plugins.socialsharing.shareViaTwitter(null, null, $scope.article.url);
}
})
What am I doing wrong here?
Because $http.get is an asynchronous call you'll have to deal with that.
Just putting it on top of your factory won't consistently work.
Try this instead:
.factory('Articles', function($http) {
return {
all: function() {
return $http.get('https://api.myjson.com/bins/4ici6').then(function(response) {
return response.data.articles;
});
},
get: function(articleId) {
//Probably best here to call an API endpoint that will return a single article with the parameter's articleId
//Something along the lines of
//$http.get('https://api.myjson.com/bins/4ic16/' + articleId).then(function(response) { //handle response});
}
};
})
Your controller should also be changed to handle the async function call:
.controller('NewsCtrl', function($scope, Articles) {
Articles.all().then(function(articles) { $scope.articles = articles });
})
You have your articles variable declared inside the callback of the http, so it won't be available outside of it. Move it outside:
.factory('Articles', function($http) {
// declaring it here makes it available in the 'all' function
var articles = [];
$http.get('https://api.myjson.com/bins/4ici6').then( function(response) {
articles = response.data.articles;
});
return {
all: function() {
return articles;
},
get: function(articleId) {
for (var i = 0; i < articles.length; i++) {
if (articles[i].id === parseInt(articleId)) {
return articles[i];
}
}
return null;
}
};
})
But because you fetch your articles asynchronously through http, it can happen that you do the Articles.all() before the articles are fetched, resulting in an empty array. Instead, I would do it like this:
.factory('Articles', function($http, $q) {
// declaring it here makes it available in the 'all' function
var articles = [];
var fetched = false;
var getAll = function() {
var deferred = $q.defer();
if (!fetched) {
$http.get('https://api.myjson.com/bins/4ici6').then( function(response) {
articles = response.data.articles;
fetched = true;
deferred.resolve(articles);
});
} else {
deferred.resolve(articles);
}
return deferred.promise;
}
return {
all: getAll,
get: function(articleId) {
var deferred = $q.defer();
getAll().then(function(articles) {
for (var i = 0; i < articles.length; i++) {
if (articles[i].id === parseInt(articleId)) {
deferred.resolve(articles[i]);
break;
}
}
// not found
return deferred.reject();
}
return deferred.promise;
}
};
})
And use it like this:
Articles.all().then(function(articles){
// now the articles are available
});
Articles.get(id).then(function(article){
// found
}, function(){
// not found
});

how to push each data from json into each array in angularjs

Im trying to push each data from json into new array, because a wanna make a graph, but it doesn't works.
What I expect is like :
f = { "FAKULTAS":"01/FKIP",
"FAKULTAS":"02/FMIPA",
"FAKULTAS":"03/FISIP" }
g = { "MASA20131":283133,
"MASA20131":2419,
"MASA20132":58719 }
This is my Json File:
{
"DARIMASA":"20131",
"KEMASA":"20142",
"ISIMASA":
[{"masa":"20131"},{"masa":"20132"},{"masa":"20141"},{"masa":"20142"}],
"DATAFAKULTAS":
[
{
"FAKULTAS":"01/FKIP",
"MASA20131":283133,
"MASA20132":26746,
"MASA20141":261238,
"MASA20142":245722
},
{
"FAKULTAS":"02/FMIPA",
"MASA20131":2419,
"MASA20132":29,
"MASA20141":2706,
"MASA20142":3207
},
{
"FAKULTAS":"03/FISIP",
"MASA20131":53312,
"MASA20132":58719,
"MASA20141":55047,
"MASA20142":53745
}]
}
Controller :
.controller("RegMhsSemesterCtrl", function ($scope, $http, chartBar4) {
$scope.data = {};
$http.get('data/RegPerSemester.json')
.success(function (data) {
var axis2 = [],seriesA = [],seriesB = [],seriesC = [],seriesD = [];
data.forEach(function(row) {
axis2.push(row.FAKULTAS);
seriesA.push(row.MASA20131);
seriesB.push(row.MASA20132);
seriesC.push(row.MASA20141);
seriesD.push(row.MASA20142);
});
$scope.data.f=axis2;
$scope.data.g=seriesA;
$scope.data.h=seriesB;
$scope.data.i=seriesC;
$scope.data.j=seriesD;
console.log($scope.data);
var i= chartBar4('chartbar4',$scope.data);
window.onresize=function ()
{
i.resize()
}
})
.error(function (error) {
$scope.data.error = error;
});
})
you can use the following code:
.controller("RegMhsSemesterCtrl", function ($scope, $http, chartBar4) {
$scope.data = {};
$http
.get('data/RegPerSemester.json')
.success(function (data) {
var DATAFAKULTAS = data.DATAFAKULTAS;
var axis2 = [],seriesA = [],seriesB = [],seriesC = [],seriesD = [];
for(var i=0; i<DATAFAKULTAS.length; i++) {
axis2.push({
"FAKULTAS": DATAFAKULTAS[i].FAKULTAS
});
seriesA.push({
"MASA20131": DATAFAKULTAS[i].MASA20131
});
.....................................................
.....................................................
}
});

TypeError: Cannot read property '0' of undefined in angular app

I'm having trouble understanding the source of an error, since html side picks up things like list[3].main.temp just fine, but in the second for loop of generateList function i get error right on the $scope.list[i].main.temp which says
TypeError: Cannot read property '0' of undefined =\
The code is supposed to take a list of 30 cities, pick random 10 and display their current temperature.
var WeatherApp = angular.module("WeatherApp", ["ngRoute", "ngResource"]).
config(function ($routeProvider) {
$routeProvider.
when('/', { controller: ListCtrl, templateUrl: 'list.html' }).
otherwise({ redirectTo: '/' });
});
WeatherApp.factory('City', function ($resource) {
return $resource('/api/City/:id', { id: '#id' }, {update: { method: 'PUT'}});
});
var ListCtrl = function ($scope, $location, City, $http) {
$scope.city = City.query();
$scope.units = 'metric';
$scope.appId = '';
$scope.displayNum = 10;
$scope.display = [];
$scope.display.temp = [];
$scope.generateList = function () {
$scope.exp = City.query(function (exp) {
shuffle(exp);
$scope.cityIdAr = [];
for (var i = 0; i < $scope.displayNum; ++i) {
$scope.display.push($scope.exp[i]);
$scope.cityIdAr.push($scope.exp[i].CityId);
};
$scope.cityId = $scope.cityIdAr.join();
$scope.getWeather();
for (var i = 0; i < $scope.displayNum; ++i) {
$scope.display.temp.push($scope.list[i].main.temp);
};
});
};
function shuffle(ob) {
for (var j, x, i = ob.length; i; j = Math.floor(Math.random() * i), x = ob[--i], ob[i] = ob[j], ob[j] = x);
return ob;
};
$scope.getWeather = function () {
var url = 'http://api.openweathermap.org/data/2.5/group';
$http.jsonp(url, {
params: {
id: $scope.cityId,
APPID: $scope.appId,
units: $scope.units,
callback : 'JSON_CALLBACK'
}
}).success(function (data, status, headers, config) {
$scope.data = data;
$scope.list = data.list;
});
};
$scope.generateList();
};
The problem may be that $scope.list is undefined until the callback is ran. You could return a promise from $scope.getWeather and resolve it in $scope.generateList, then execute the for loop when the data is retrieved (inside the callback) e.g.
Return a promise from $scope.getWeather:
$scope.getWeather = function () {
...
return $http.jsonp(...)
}
and then in $scope.generateList:
...
$scope.getWeather().success(function(data, status, headers, config) {
$scope.data = data;
$scope.list = data.list;
for (var i = 0; i < $scope.displayNum; ++i) {
$scope.display.temp.push($scope.list[i].main.temp);
};
}
or something along these lines.
$scope.display is a List use another variable
var WeatherApp = angular.module("WeatherApp", ["ngRoute", "ngResource"]).
config(function ($routeProvider) {
$routeProvider.
when('/', { controller: ListCtrl, templateUrl: 'list.html' }).
otherwise({ redirectTo: '/' });
});
WeatherApp.factory('City', function ($resource) {
return $resource('/api/City/:id', { id: '#id' }, {update: { method: 'PUT'}});
});
var ListCtrl = function ($scope, $location, City, $http) {
$scope.city = City.query();
$scope.units = 'metric';
$scope.appId = '';
$scope.displayNum = 10;
$scope.display = [];
$scope.temp = [];
$scope.generateList = function () {
$scope.exp = City.query(function (exp) {
shuffle(exp);
$scope.cityIdAr = [];
for (var i = 0; i < $scope.displayNum; ++i) {
$scope.display.push($scope.exp[i]);
$scope.cityIdAr.push($scope.exp[i].CityId);
};
$scope.cityId = $scope.cityIdAr.join();
$scope.getWeather();
for (var i = 0; i < $scope.displayNum; ++i) {
$scope.temp.push($scope.list[i].main.temp);
};
});
};
function shuffle(ob) {
for (var j, x, i = ob.length; i; j = Math.floor(Math.random() * i), x = ob[--i], ob[i] = ob[j], ob[j] = x);
return ob;
};
$scope.getWeather = function () {
var url = 'http://api.openweathermap.org/data/2.5/group';
$http.jsonp(url, {
params: {
id: $scope.cityId,
APPID: $scope.appId,
units: $scope.units,
callback : 'JSON_CALLBACK'
}
}).success(function (data, status, headers, config) {
$scope.data = data;
$scope.list = data.list;
});
};
$scope.generateList();
};

AngularJS set var: http get

I have an angular filter set up which works great:
categorieFilter = angular.module("categorieFilter", [])
categorieFilter.controller("catFilter", ["$scope", "store", function($scope, store){
$scope.search = "";
$scope.products = [];
$scope.categories = [];
$scope.categories = store.getCategories();
$scope.products = store.getProducts();
$scope.filterProductsByCats = function(category){
$scope.search = category;
};
}])
categorieFilter.factory('store', function(){
var categories = ['Lattes','CC Blend','Frappes'];
var products = [
{name: 'Latte machiatto',category: 'Lattes'},
{name: 'Frappe ice',category: 'Frappes'},
{name: 'Latte caramel',category: 'Lattes'},
{name: 'Frappe speculoos',category: 'Frappes'},
{name: 'Cappucino',category: 'CC Blend'},
{name: 'Filter coffee',category: 'CC Blend'},
];
return {
getCategories : function(){
return categories;
},
getProducts : function(){
return products;
}
};
});
But the var categories and var products are still hard coded so I want to retreive the needed data from my server to fill these variables. And I can't seem to get this right? I have another function where I can get the required data but I don't know how I can get these 2 in 1...?
categories = angular.module('categories', []);
categories.controller("category",function($scope, $http){
var serviceBase = 'api/';
$http.get(serviceBase + 'categories').then(function (results) {
$scope.categories = results.data;
for(var i = 0; i < $scope.categories.length; i++){
var categories = $scope.categories[i];
}
});
});
So how can I properly set the var categories to the required $http.get to retreive my server data into the filter above?
I think you should be able to get rid of the hard coded block in the service and just return:
return {
getCategories: $http.get('/categories').success(function (data) {
return data;
}),
getProducts: $http.get('/products').success(function (data) {
return data;
})
}
Make sure you dependencies are setup correctly for the service though (i.e. $http):
.factory('store', function ($http) {
// The above return block here
});
And this should do the trick!

Parse xml tag in a AngularJS feed

I need parse the enclosure tag in order to get the url image. It's assumed I should get the MIXED OUTPUT with the json+xml code but I get a undefined value from the enclousure tag when I try parse it. I'm doing this like I saw at this post > Google Feed Loader API ignoring XML attributes < .In addition I tried to get the MIXED format writing the url manually but It doesn't work. There is my whole code. How could I know that Im getting the mixed json output?
var feeds = [];
var entryImageUrl = [];
angular.module('starter.controllers', ['ngResource','ngLocale'])
.factory('FeedLoader', function ($resource) {
return $resource('http://ajax.googleapis.com/ajax/services/feed/load', {}, {
fetch: { method: 'JSONP', params: {v: '1.0', callback: 'JSON_CALLBACK', output: 'json_xml'} }
});
})
.service('FeedList', function ($rootScope, FeedLoader) {
this.get = function() {
var feedSources = [
{title: 'Heraldo De Barbate', url: 'http://www.heraldodebarbate.es/rss/last'},
];
if (feeds.length === 0) {
for (var i=0; i<feedSources.length; i++) {
FeedLoader.fetch({q: feedSources[i].url, num: 10}, {}, function (data) {
var feed = data.responseData.feed;
**var entryImageUrl = feed.xmlNode.getElementsByTagName("enclosure")[i].getAttribute("url");**
feeds.push(feed);
});
}
}
return feeds;
};
})
.controller('FeedCtrl', function ($scope, FeedList,$timeout) {
$scope.update = function(){
$scope.feeds = FeedList.get();
$scope.$on('FeedList', function (event, data) {
$scope.feeds = data;
// $scope.entryImageUrl
console.log(feeds);
});
$timeout(function() {
$scope.$broadcast('scroll.refreshComplete');
}, 500);
}
})
How could I know that Im getting the mixed json output?
Use a test for tags within JSON:
function testMe(node)
{
return /</.test(JSON.stringify(node) )
}
then run it on the feed:
var mixed_format = testMe(feed);
and call another function which parses the data:
if (mixed_format)
{
mixed_parser(feed)
}
else
{
json_parser(feed)
}

Categories