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'
}
]
}
};
}])
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'm trying to use high charts via angular to take advantage of double binding. I'm having an issue rendering the data, the graph works but the data is not showing up in the chart. When I check the DOM console I can get the array but for some reason its not showing up in the graph.
cpvmPartners = [];
cpvmPlannedCpm = [];
actualCpm = [];
graphData = [];
cpvm = [];
plannedPrepared = [];
getData = function(){
$.getJSON('/cpvmdata', function(data) {
for(k in data){
if(data[k]['audience'] == 'GCM'){
graphData.push([data[k]['partner'],data[k]['plannedcpm']])
actualCpm.push(Math.round((data[k]['mediacost']/data[k]['impressions']*1000)))
cpvmPlannedCpm.push(data[k]['plannedcpm'])
cpvmPartners.push(data[k]['partner'])
}
}
});
}
prepareData = function(){
for(var i = 0; i < actualCpm.length; i++) {
actualPrepared.push({name: "CPM", data: actualCpm[i]})
plannedPrepared.push({name: "Planned CPM", data: cpvmPlannedCpm[i]})
}
}
myApp = angular.module('main', ['highcharts-ng']);
myApp.controller('graphController', function ($scope) {
getData();
prepareData();
$scope.highchartsNG = {
options: {
chart: {
type: 'bar'
}
},
series: [{
data: actualCpm
}],
title: {
text: 'Hello'
},
loading: false
}
});
So the getData() function you call in the angular controller is asynchronous:
By the time you have gotten the data, you have already made your chart in $scope.highChartNg
That is why you can see your data the console but you don't actually set it to the actualCpm by the time angular is done. To fix this you need to create the chart IN your $.getJSON function like so:
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: [{}]
};
$.getJSON('data.json', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
You can see more here: http://www.highcharts.com/docs/working-with-data/custom-preprocessing
Easier just to use
$http.get
Angular service.
Blending jQuery and Angular is troublesome for scoping.
$http.get('cpvmdata')
.then(function(response){
$scope.output = response.data;
for(k in $scope.output){
if($scope.output[k]['audience'] == 'GCM'){
$scope.planned.push($scope.output[k]['plannedcpm'])
$scope.partners.push($scope.output[k]['partner'])
$scope.cpm.push(Math.round(($scope.output[k]['mediacost']/$scope.output[k]['impressions']*1000)))
}
}
});
I have a uigrid that contains a large number of column definitions that aren't initially filled with data because the data set would be too large. Instead, I get the requested column data when the column visibility changes.
This causes an issue with the built in csv exporter. When someone chooses to "Export all data as csv" they get numerous empty columns.
What I would like to do it change the default behavior of the built in csv menu items to use uiGridExporterConstants.VISIBLE.
I was going to roll my own menu items like so:
$scope.gridOptions.exporterMenuCsv = false; //Rolling our own menu items to exclude invisible columns
$scope.gridOptions.gridMenuCustomItems = [
{
title: 'Export All to CSV',
action: function ($event) {
var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
$scope.gridApi.exporter.csvExport( uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, myElement );
}
},{
title: 'Export Selected to CSV',
action: function ($event) {
var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
$scope.gridApi.exporter.csvExport( uiGridExporterConstants.SELECTED, uiGridExporterConstants.VISIBLE, myElement );
}
},{
title: 'Export Visible to CSV',
action: function ($event) {
var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
$scope.gridApi.exporter.csvExport( uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE, myElement );
}
}
];
But only the first item appears. Maybe I have to use addToGridMenu, but I'm not sure. Ideally, I'd like to leave the default items in place, but just have "export all data as csv" only export the visible columns.
I ended up having to use gridApi.core.addToGridMenu like so:
$scope.gridOptions = {
exporterCsvLinkElement: angular.element(document.querySelectorAll('.custom-csv-link-location')),
onRegisterApi: function(gridApi){
$scope.gridApi = gridApi;
$interval(function () {
gridApi.core.addToGridMenu(gridApi.grid, [{
title: 'Export All to CSV',
order: 1,
action: function ($event) {
var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
$scope.gridApi.exporter.csvExport(uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, myElement);
}
}]);
gridApi.core.addToGridMenu(gridApi.grid, [{
title: 'Export Visible to CSV',
order: 2,
action: function ($event) {
var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
$scope.gridApi.exporter.csvExport(uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE, myElement);
}
}]);
}, 0, 1);
$scope.gridApi.selection.on.rowSelectionChanged($scope, function () { //for single row selection
if (gridApi.grid.selection.selectedCount > 0 && !selectionMenuAdded) { //only add menu item if something is selected and if the menu item doesn't already exist
selectionMenuAdded = true;
gridApi.core.addToGridMenu(gridApi.grid, [{
title: 'Export Selected to CSV',
order: 3,
id: 'uiSel',
action: function ($event) {
if (gridApi.grid.selection.selectedCount > 0) {
var uiExporter = uiGridExporterService;
var grid = $scope.gridApi.grid;
uiExporter.loadAllDataIfNeeded(grid, uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE).then(function () {
var exportColumnHeaders = uiExporter.getColumnHeaders(grid, uiGridExporterConstants.VISIBLE);
var selectionData = [];
gridApi.selection.getSelectedRows().forEach(function (entry) {
var innerData = [];
for (var e in entry) { //create the inner data object array
if (e !== '$$hashKey') {
var selectObj = { value: entry[e] };
innerData.push(selectObj);
}
}
selectionData.push(innerData); //push the inner object value array to the larger array as required by formatAsCsv
});
var csvContent = uiExporter.formatAsCsv(exportColumnHeaders, selectionData, grid.options.exporterCsvColumnSeparator);
uiExporter.downloadFile($scope.gridOptions.exporterCsvFilename, csvContent, grid.options.exporterOlderExcelCompatibility);
});
}
}
}]);
} else if (gridApi.grid.selection.selectedCount === 0 && selectionMenuAdded) {
selectionMenuAdded = false;
gridApi.core.removeFromGridMenu(gridApi.grid, 'uiSel');
}
});
$scope.gridApi.selection.on.rowSelectionChangedBatch($scope, function () {
if (gridApi.grid.selection.selectedCount > 0 && !selectionMenuAdded) {
selectionMenuAdded = true;
gridApi.core.addToGridMenu(gridApi.grid, [{
title: 'Export Selected to CSV',
order: 3,
id: 'uiSel',
action: function ($event) {
if (gridApi.grid.selection.selectedCount > 0) {
var uiExporter = uiGridExporterService;
var grid = $scope.gridApi.grid;
uiExporter.loadAllDataIfNeeded(grid, uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE).then(function () {
var exportColumnHeaders = uiExporter.getColumnHeaders(grid, uiGridExporterConstants.VISIBLE);
var selectionData = [];
gridApi.selection.getSelectedRows().forEach(function (entry) {
var innerData = [];
for (var e in entry) {
if (e !== '$$hashKey') {
var selectObj = { value: entry[e] };
innerData.push(selectObj);
}
}
selectionData.push(innerData);
});
var csvContent = uiExporter.formatAsCsv(exportColumnHeaders, selectionData, grid.options.exporterCsvColumnSeparator);
uiExporter.downloadFile($scope.gridOptions.exporterCsvFilename, csvContent, grid.options.exporterOlderExcelCompatibility);
});
}
}
}]);
} else if (gridApi.grid.selection.selectedCount === 0 && selectionMenuAdded) {
selectionMenuAdded = false;
gridApi.core.removeFromGridMenu(gridApi.grid, 'uiSel');
}
});
}
}
Be sure to inject uiGridExporterConstants and uiGridExporterService.
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!
I am looking to run the following controller but im having trouble with scope.
I have a service that calls two functions that retrieve meta data to populate scope variables.
The issue is that using the service to call back the data interferes with other actions happening in the code. I have a directive on a tag that shows/hides an error on the span element once the rule is validated. This is now not functioning correctly. I run the code without asynchronous functions then everything works correctly.
My Plunker code is here
and the plunker of the desired behaviour is here
Plunker working example without dynamic data loading
<form class="form-horizontal">
<div class="control-group" ng-repeat="field in viewModel.Fields">
<label class="control-label">{{field.label}}</label>
<div class="controls">
<input type="text" id="{{field.Name}}" ng-model="field.data" validator="viewModel.validator" ruleSetName="{{field.ruleSet}}"/>
<span validation-Message-For="{{field.Name}}"></span>
</div>
</div>
<button ng-click="save()">Submit</button>
</form>
How do I get all bindings to update so everything is sync and loaded correctly?
angular.module('dataApp', ['servicesModule', 'directivesModule'])
.controller('dataCtrl', ['$scope', 'ProcessService', 'ValidationRuleFactory', 'Validator',
function($scope, ValidationRuleFactory, Validator, ProcessService) {
$scope.viewModel = {};
var FormFields = {};
// we would get this from the meta api
ProcessService.getProcessMetaData().then(function(data) {
alert("here");
FormFields = {
Name: "Course",
Fields: [{
type: "text",
Name: "name",
label: "Name",
data: "",
required: true,
ruleSet: "personFirstNameRules"
}, {
type: "text",
Name: "description",
label: "Description",
data: "",
required: true,
ruleSet: "personEmailRules"
}]
};
$scope.viewModel.Fields = FormFields;
ProcessService.getProcessRuleData().then(function(data) {
var genericErrorMessages = {
required: 'Required',
minlength: 'value length must be at least %s characters',
maxlength: 'value length must be less than %s characters'
};
var rules = new ValidationRuleFactory(genericErrorMessages);
$scope.viewModel.validationRules = {
personFirstNameRules: [rules.isRequired(), rules.minLength(3)],
personEmailRules: [rules.isRequired(), rules.minLength(3), rules.maxLength(7)]
};
$scope.viewModel.validator = new Validator($scope.viewModel.validationRules);
});
});
var getRuleSetValuesMap = function() {
return {
personFirstNameRules: $scope.viewModel.Fields[0].data,
personEmailRules: $scope.viewModel.Fields[1].data
};
};
$scope.save = function() {
$scope.viewModel.validator.validateAllRules(getRuleSetValuesMap());
if ($scope.viewModel.validator.hasErrors()) {
$scope.viewModel.validator.triggerValidationChanged();
return;
} else {
alert('person saved in!');
}
};
}
]);
The validation message directive is here
(function(angular, $) {
angular.module('directivesModule')
.directive('validationMessageFor', [function() {
return {
restrict: 'A',
scope: {eID: '#val'},
link: function(scope, element, attributes) {
//var errorElementId = attributes.validationMessageFor;
attributes.$observe('validationMessageFor', function(value) {
errorElementId = value;
//alert("called");
if (!errorElementId) {
return;
}
var areCustomErrorsWatched = false;
var watchRuleChange = function(validationInfo, rule) {
scope.$watch(function() {
return validationInfo.validator.ruleSetHasErrors(validationInfo.ruleSetName, rule.errorCode);
}, showErrorInfoIfNeeded);
};
var watchCustomErrors = function(validationInfo) {
if (!areCustomErrorsWatched && validationInfo && validationInfo.validator) {
areCustomErrorsWatched = true;
var validator = validationInfo.validator;
var rules = validator.validationRules[validationInfo.ruleSetName];
for (var i = 0; i < rules.length; i++) {
watchRuleChange(validationInfo, rules[i]);
}
}
};
// get element for which we are showing error information by id
var errorElement = $("#" + errorElementId);
var errorElementController = angular.element(errorElement).controller('ngModel');
var validatorsController = angular.element(errorElement).controller('validator');
var getValidationInfo = function() {
return validatorsController && validatorsController.validationInfoIsDefined() ? validatorsController.validationInfo : null;
};
var validationChanged = false;
var subscribeToValidationChanged = function() {
if (validatorsController.validationInfoIsDefined()) {
validatorsController.validationInfo.validator.watchValidationChanged(function() {
validationChanged = true;
showErrorInfoIfNeeded();
});
// setup a watch on rule errors if it's not already set
watchCustomErrors(validatorsController.validationInfo);
}
};
var getErrorMessage = function(value) {
var validationInfo = getValidationInfo();
if (!validationInfo) {
return '';
}
var errorMessage = "";
var errors = validationInfo.validator.errors[validationInfo.ruleSetName];
var rules = validationInfo.validator.validationRules[validationInfo.ruleSetName];
for (var errorCode in errors) {
if (errors[errorCode]) {
var errorCodeRule = _.findWhere(rules, {errorCode: errorCode});
if (errorCodeRule) {
errorMessage += errorCodeRule.validate(value).errorMessage;
break;
}
}
}
return errorMessage;
};
var showErrorInfoIfNeeded = function() {
var validationInfo = getValidationInfo();
if (!validationInfo) {
return;
}
var needsAttention = validatorsController.ruleSetHasErrors() && (errorElementController && errorElementController.$dirty || validationChanged);
if (needsAttention) {
// compose and show error message
var errorMessage = getErrorMessage(element.val());
// set and show error message
element.text(errorMessage);
element.show();
} else {
element.hide();
}
};
subscribeToValidationChanged();
if (errorElementController)
{
scope.$watch(function() {
return errorElementController.$dirty;
}, showErrorInfoIfNeeded);
}
scope.$watch(function() {
return validatorsController.validationInfoIsDefined();
}, subscribeToValidationChanged());
});
}
};
}]);
})(angular, $);