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);
};
});
Related
I want to push some field from json object that look like that
{
"type": "tasks",
"levels": 3,
"links": [
{
....
}
],
"assignedDate": "2017-08-02 16:03:36",
"number": 200612,
"priority": 3,
"createdDate": "2017-08-02 16:03:36",
"state": "ASSIGNED",
"ownerRole": "LoanApplication.Process Owner",
"processName": "LoanProcess",
.
.
.
}
in ko.observableArray. this is my JS code (i am using oracle jet )
define(['ojs/ojcore', 'knockout', 'ojs/ojtable'], function (oj, ko) {
function homeContentViewModel() {
var self = this;
self.data = ko.observableArray();
$.getJSON("http://localhost:8085/get/bpm").
then(function (taches) {
$.each(taches, function () {
self.data.push({
title: this.type,
releaseYear: this.levels,
director: this.title
});
});
});
self.dataSource = new oj.ArrayTableDataSource(
self.data,
{idAttribute: 'title'}
);
}
return homeContentViewModel;
});
ps: when i change the JSON object to a JSON array it work
Any help is appreciated.
function Model(opt_data) {
var data = opt_data || {};
var self = this;
self.taches = ko.observableArray([]); // with ([])
for (var i = 0; i < data.taches.length; i++) {
var tache = new Tache(data.taches[i]);
self.taches.push(tache);
}
}
function Tache(opt_data) {
var data = opt_data || {};
var self = this;
self.title = ko.observable(data.type || "");
self.releaseYear = ko.observable(data.levels || "");
self.director = ko.observable(data.title || "");
}
var vm = new Model(dataJson); //Your json with some data
ko.applyBindings(vm);
Thanks to #user3297291 this one worked
define(['ojs/ojcore', 'knockout', 'ojs/ojtable'], function (oj, ko) {
function homeContentViewModel() {
var self = this;
self.data = ko.observableArray();
$.getJSON("http://localhost:8085/get/bpm").
then(function (taches) {
self.data.push({
title: this.type,
releaseYear: this.levels,
director: this.title
});
});
self.dataSource = new oj.ArrayTableDataSource(
self.data,
{idAttribute: 'title'}
);
}
return homeContentViewModel;
});
Anyone can help with this? Can't update var ABCKey. Execute setAuthenticatedAccount and console.log return correct value. After that, run getAuthenticatedAccount, and receive undefined.
angular.module('authentication.service', [
])
.factory('Authentication', ['$state', '$cookies', '$http', 'app', 'routes', 'cfCryptoHttpInterceptor',
function($state, $cookies, $http, app, routes, cfCryptoHttpInterceptor) {
var ABCKey;
var setAuthenticatedAccount = function (account, tokenAuth) {
var accountInfo = {'email': account.email, 'username': account.username, 'token': tokenAuth}
var abc = CryptoJS.enc.Base64.parse(account.abc);
Authentication.setABCKey(abc);
console.log(Authentication.showABCKey())
}
var getAuthenticatedAccount = function() {
if(!$cookies.authenticatedAccount) {
return;
}
console.log(Authentication.showABCKey())
}
var setABCKey = function(key) {
ABCKey = key;
};
var showABCKey = function() {
return ABCKey;
};
var Authentication = {
setAuthenticatedAccount: setAuthenticatedAccount,
getAuthenticatedAccount: getAuthenticatedAccount,
setABCKey: setABCKey,
showABCKey: showABCKey
};
return Authentication;
}]);
Remove Authentication while you are calling your functions because it is creating object every time. And also set var ABCKey=null at the time of decelaration like this-
angular.module('authentication.service', [
])
.factory('Authentication', ['$state', '$cookies', '$http', 'app', 'routes', 'cfCryptoHttpInterceptor',
function($state, $cookies, $http, app, routes, cfCryptoHttpInterceptor) {
var ABCKey=null;
var setAuthenticatedAccount = function (account, tokenAuth) {
var accountInfo = {'email': account.email, 'username': account.username, 'token': tokenAuth}
var abc = CryptoJS.enc.Base64.parse(account.abc);
setABCKey(abc);
console.log(showABCKey())
}
var getAuthenticatedAccount = function() {
if(!$cookies.authenticatedAccount) {
return;
}
console.log(showABCKey())
}
var setABCKey = function(key) {
ABCKey = key;
};
var showABCKey = function() {
return ABCKey;
};
var Authentication = {
setAuthenticatedAccount: setAuthenticatedAccount,
getAuthenticatedAccount: getAuthenticatedAccount,
setABCKey: setABCKey,
showABCKey: showABCKey
};
return Authentication;
}]);
dont use var its single tone class you need to define ABCkey in this
var ABCKey;
try with this
this.ABCKey = '';
I have a chart, using angular-chart.js, which the x and y axis values varies depending on which item a user clicks on. When one of the items is clicked, it omits the first unit so instead of displaying 2.52 it displays .52. If you see below, the log is showing the correct information, just not displaying it.
The website I have provided a link to above provides examples which I have followed and I am a bit stumped why this is happening. It is quite lengthy my code for populting the chart with the correct data but I will try and provide only the necessary code.
Any ideas why the correct value isn't being displayed in the Y axis?
service which gathers the data for the graph
app.factory('loadPatentItemService', ['$http', '$timeout', function($http, $timeout) {
var factory = {};
var selectedData = null;
var selectedLabel = null;
var selectedItem = null;
var REST_SERVICE_URI = '../json/cost-data.json';
//function is invoked from the view and data is passed depending which item was clicked
factory.select = function(item) {
selectedItem = item;
factory.getPatent();
return [selectedItem];
}
factory.getPatent = function() {
var itemId = [];
itemId.push(selectedItem.id)
$http.get(REST_SERVICE_URI)
.then(function(response){
var items = response.data.dataset;
var graphData = [];
var graphLabel = [];
for (i = 0;i < items.length; i++) {
if(items[i].id == itemId) {
graphData.push(items[i].data);
graphLabel.push(items[i].label);
factory.graphLabel(graphLabel);
factory.graphData(graphData);
}
}
}),
function(errResponse) {
console.log('error')
}
return selectedItem;
}
factory.graphData = function(data) {
selectedData = data;
return [data];
}
factory.graphLabel = function(label) {
selectedLabel = label;
return [label];
}
factory.getData = function() {
return selectedData;
}
factory.getLabel = function() {
return selectedLabel;
}
return factory;
}])
graph controller
app.controller("lineCtrl", ['$scope', '$timeout', 'loadPatentItemService', function ($scope, $timeout, loadPatentItemService) {
var initGraph = loadPatentItemService.getPatent();
var getGraphData = loadPatentItemService.getData();
var getGraphLabel = loadPatentItemService.getLabel();
$scope.labels = getGraphLabel[0];
$scope.data = getGraphData[0];
console.log(getGraphData[0], getGraphLabel[0])
$scope.datasetOverride = [{ yAxisID: 'y-axis-1' }, { yAxisID: 'y-axis-2' }];
$scope.options = {
scales: {
yAxes: [
{
id: 'y-axis-1',
type: 'linear',
display: true,
position: 'left'
},
{
id: 'y-axis-2',
type: 'linear',
display: true,
position: 'right'
}
]
}
};
}])
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
});
.....................................................
.....................................................
}
});
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!