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
});
.....................................................
.....................................................
}
});
Related
I have an array in data_controller.js and i wanted my main.js, where I edit my angular chart there, to be able to fetch the array. Any specific way on doing this?
Data_Controller.js:
/*global angular*/
var app = angular.module('statisticsApp', [chart.js]).controller('myCtrl',
function ($scope, $http) {
"use strict";
return $http({
method : "POST",
url : "GatewayAPI.php",
}).then(function mySuccess(response) {
$scope.records = response.data;
var mydata,myJSON,myresult,myjava, myobj;
var i;
var Result;
var chartResultTemp = [];
var chartResultph = [];
var chartResultHum = [];
var resultType = [];
for(i=0; i<72;i++)
{
//storing data
mydata = $scope.records.data[i];
//retrieving data
myobj = mydata.data.substring(3,4);
resultType = mydata.data.substring(3, 4);
if(resultType === "A") {
chartResultTemp.push([mydata.data.substring(6,9)]);
} else if (resultType ==="B") {
chartResultph.push([mydata.data.substring(6, 9)]);
} else {
chartResultHum.push([mydata.data.substring(6, 9)]);
};
$scope.test=Result; //change to array
$scope.test2=chartResultTemp;
$scope.test3 = resultType;
$scope.test4 = chartResultph;
$scope.test5 = chartResultHum;
console.log(Result);
console.log(resultType);
}
$scope.gotTemp = false;
$scope.gotHumidity = false;
$scope.getSoilMoisture = false;
});
});
main.js:
var app = angular.module("statisticsApp", ["chart.js"]);
app.controller("LineCtrl", function ($scope) {
"use strict";
$scope.labels = ["0200", "0400", "0600", "0800", "1000", "1200", "1400",
"1600", "1800", "2000", "2200", "0000"];
$scope.series = ['Temperature (°C)'];
$scope.data = [
[26.5, 26.8, 26.3, 25.8, 29.4, 30.2, 31.5, 31.0, 28.4, 27.6, 26.3, 25.7]
];
$scope.onClick = function (points, evt) {
console.log(points, evt);
};
});
I have tried putting the chart function from main,js into data_controller.js and wrote $scope.data.push([mydata.data.substring(6,9)]) but that did nothing.
How do I call the function in data_controller.js and use the array in my $scope.data = [] in main.js?
If you want to reuse that method for retrieving data, it would be best to decouple it into a service. Then, you can use it all of your controllers.
Please note that code below is just to showcase the implementation, it might not work straight away if you just copy-paste it.
//statisticsSvc.js
angular.module('statisticsApp').service('statisticsService',['$http' function($http){
var data = [];
return {
getStatistics: function(){
return $http({
method : "POST",
url : "GatewayAPI.php",
})
.then(function(response){
var mydata,myJSON,myresult,myjava, myobj;
var i;
var Result;
var chartResultTemp = [];
var chartResultph = [];
var chartResultHum = [];
var resultType = [];
for(i=0; i<72;i++)
{
//storing data
mydata = response.data.data[i];
//retrieving data
myobj = mydata.data.substring(3,4);
resultType = mydata.data.substring(3, 4);
if(resultType === "A") {
chartResultTemp.push([mydata.data.substring(6,9)]);
} else if (resultType ==="B") {
chartResultph.push([mydata.data.substring(6, 9)]);
} else {
chartResultHum.push([mydata.data.substring(6, 9)]);
};
return {
records: response.data.data,
Result: Result,
chartResultTemp: chartResultTemp,
resultType: resultType,
chartResultph: chartResultph,
chartResultHum: chartResultHum
};
}
})
.catch(function(error){
console.log(error);
return error;
})
},
setData: function(a){ data = a;},
getData: function(){ return data;}
};
}]);
Then, you can use this service in your controllers:
//myCtrl
var app = angular.module('statisticsApp', [chart.js]).controller('myCtrl',
function ($scope, $http,statisticsService) {
//your call to service
statisticsService.getStatistics().then(function(response){
$scope.records = response.records;
$scope.test = response.Result;
$scope.test2 = response.chartResultTemp;
$scope.test3 = response. resultType;
}).error(function(error){
console.log(error);
});
//get data
$scope.data = statisticsService.getData();
});
//LineCtrl
var app = angular.module("statisticsApp", ["chart.js"]);
app.controller("LineCtrl", function ($scope, statisticsService) {
"use strict";
$scope.labels = ["0200", "0400", "0600", "0800", "1000", "1200", "1400",
"1600", "1800", "2000", "2200", "0000"];
$scope.series = ['Temperature (°C)'];
$scope.data = [
[26.5, 26.8, 26.3, 25.8, 29.4, 30.2, 31.5, 31.0, 28.4, 27.6, 26.3, 25.7]
];
//set data
statisticsService.setData($scope.data);
$scope.onClick = function (points, evt) {
console.log(points, evt);
};
});
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,
};
}
})
})
})();
I am trying to parse in my HTML page many JSON files:
Here is my service's code:
app.factory('myapp', ['$http', function($http) {
var tab = ['url1', 'url2', 'url3']
for(i=0; i<tab.length; i++){
return $http.get(tab[i])
.success(function(data) {
return data;
})
.error(function(err) {
return err;
}); }
}]);
In my HTML file , I only have the information of the first json file.
Here's my HTML code:
<tr>
<td>{{data.nm}}</td>
<td>{{data.cty}}</td>
<td>{{data.hse}}</td>
<td>{{data.yrs}}</td>
</tr>
Is there something to add in my HTML so I can get the information from all the json files or any other solution?
First off, you return in the first iteration in your for loop, so you only get the data for the first url. Don't return right away, assign a scope variable to your data:
Factory
app.factory('myapp', ['$http', function($http) {
function getLists() {
var tab = ['url1', 'url2', 'url3'];
var list = [];
for(i=0; i<tab.length; i++){
$http.get(tab[i])
.then(function(res) {
list.push(res.data);
});
}
return list;
}
return {
getLists: getLists
};
]);
Controller
$scope.list = myapp.getLists();
HTML
<tr ng-repeat="d in list">
<td>{{d.nm}}</td>
<td>{{d.cty}}</td>
<td>{{d.hse}}</td>
<td>{{d.yrs}}</td>
</tr>
I think what you are looking for is $q.all
I would solve the problem like this
angular.module('app').factory('myRequestsFactory',function($http, apiHost) {
var myRequestsFactory = {};
myRequestsFactory.geturl1 = function() {
return $http.get(url1);
};
myRequestsFactory.geturl2 = function() {
return $http.get(url2);
};
myRequestsFactory.geturl3 = function() {
return $http.get(url3);
};
return myRequestsFactory;
});
Then I would create an other service
angular.module('app').factory('helperService',function($q, myRequestsFactory) {
var helperService = {};
helperService.GetAll = function() {
return $q.all([
myRequestsFactory.geturl1(),
myRequestsFactory.geturl2(),
myRequestsFactory.geturl3() ]);
};
return helperService;
});
Then in my controller ..
function loadData() {
helperService.GetAll().then(
function(result) {
$scope.url1result = result[0];
$scope.url2result = result[1];
$scope.url3result = result[2];
});
},
function(error) {
}
);
}
That's how i would get access to this data
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();
};
here are lines from a built in directive(blueimp)
.controller('FileUploadController', [
'$scope', '$element', '$attrs', '$window', 'fileUpload',
function ($scope, $element, $attrs, $window, fileUpload) {
alert('incontroller');
var uploadMethods = {
progress: function () {
return $element.fileupload('progress');
},
active: function () {
return $element.fileupload('active');
},
option: function (option, data) {
return $element.fileupload('option', option, data);
},
add: function (data) {
return $element.fileupload('add', data);
},
send: function (data) {
return $element.fileupload('send', data);
},
process: function (data) {
return $element.fileupload('process', data);
},
processing: function (data) {
return $element.fileupload('processing', data);
}
};
$scope.disabled = !$window.jQuery.support.fileInput;
$scope.queue = $scope.queue || [];
$scope.clear = function (files) {
var queue = this.queue,
i = queue.length,
file = files,
length = 1;
if (angular.isArray(files)) {
file = files[0];
length = files.length;
}
while (i) {
i -= 1;
if (queue[i] === file) {
return queue.splice(i, length);
}
}
};
$scope.replace = function (oldFiles, newFiles) {
var queue = this.queue,
file = oldFiles[0],
i,
j;
for (i = 0; i < queue.length; i += 1) {
if (queue[i] === file) {
for (j = 0; j < newFiles.length; j += 1) {
queue[i + j] = newFiles[j];
}
return;
}
}
};
$scope.applyOnQueue = function (method) {
var list = this.queue.slice(0),
i,
file;
for (i = 0; i < list.length; i += 1) {
file = list[i];
if (file[method]) {
file[method]();
}
}
};
$scope.submit = function () {
this.applyOnQueue('$submit');
};
$scope.cancel = function () {
this.applyOnQueue('$cancel');
};
// Add upload methods to the scope:
angular.extend($scope, uploadMethods);
// The fileupload widget will initialize with
// the options provided via "data-"-parameters,
// as well as those given via options object:
$element.fileupload(angular.extend(
{scope: function () {
return $scope;
}},
fileUpload.defaults
)).on('fileuploadadd', function (e, data) {
data.scope = $scope.option('scope');
}).on('fileuploadchange', function (e, data) {
data.scope = $scope.option('scope');
data.scope.extend({
mycustomfield:$element
//i added above line, is it illegal, or too ugly to get element,or needless,some other way?
});
}).on([
'fileuploadadd',
'fileuploadsubmit',
'fileuploadsend',
'fileuploaddone',
'fileuploadfail',
'fileuploadalways',
'fileuploadprogress',
'fileuploadprogressall',
'fileuploadstart',
'fileuploadstop',
'fileuploadchange',
'fileuploadpaste',
'fileuploaddrop',
'fileuploaddragover',
'fileuploadchunksend',
'fileuploadchunkdone',
'fileuploadchunkfail',
'fileuploadchunkalways',
'fileuploadprocessstart',
'fileuploadprocess',
'fileuploadprocessdone',
'fileuploadprocessfail',
'fileuploadprocessalways',
'fileuploadprocessstop'
].join(' '), function (e, data) {
if ($scope.$emit(e.type, data).defaultPrevented) {
e.preventDefault();
}
}).on('remove', function () {
// Remove upload methods from the scope,
// when the widget is removed:
var method;
for (method in uploadMethods) {
if (uploadMethods.hasOwnProperty(method)) {
delete $scope[method];
}
}
});
// Observe option changes:
$scope.$watch(
$attrs.fileUpload,
function (newOptions) {
if (newOptions) {
$element.fileupload('option', newOptions);
}
}
);
}
])
.directive('fileUpload', function () {
return {
controller: 'FileUploadController',
scope: true
};
})
i can see reaction on my template controller
$scope.$on('fileuploadchange',function(e,data){
//here i want to get element which is the source of event
//if you can look at above code piece, i think i can get the element by
//data.scope.mycustomfield
}
some nicer way?