I am new in AngularJS.
I download AngularJS theme from URL here
I have to get Data from GET Service.
GET Service URL is given below
http://localhost:8080/api/getHostStatus
that is running correctly.
So I have to use this URL and get data from that service for this I just change the code in my VisitorsController.js
VisitorsController.js file code is given below
(function () {
angular
.module('app')
.controller('VisitorsController', [
VisitorsController
]);
function VisitorsController() {
var vm = this;
// TODO: move data to the service
var servicesUrl = app.serviceCallUrl+'getHostStatus';
console.log(servicesUrl);
var myService = angular.module("app").factory("myService", ['$http', function($http) {
return {
getResponders: (function(response) {
return $http.get(servicesUrl).then(function(response) {
console.log(response.data);
return response.data;
});
})()
};
return myService;
}]);
vm.visitorsChartData = [ {key: 'UP', y: 5264}, { key: 'Critical', y: 3872},{key: 'Warning', y: 1000} ];
vm.chartOptions = {
chart: {
type: 'pieChart',
height: 210,
donut: true,
x: function (d) { return d.key; },
y: function (d) { return d.y; },
valueFormat: (d3.format(".0f")),
color: ['rgb(0, 150, 136)', '#E75753','#fbbc05'],
showLabels: false,
showLegend: false,
title: 'Over 9K',
margin: { top: -10 }
}
};
}
})();
When I run this it is showing me correct servicesUrl on console.
But response.data not showing on console.
So please guide me how can I resolve it.
Related
I am trying to plot a graph with Hightchart, my data comes from an REST web service.
I am using angularjs (1.5) to get the data.
my Service look like :
app.factory('ServicesImpl', function($http){
var obj = {};
obj.getData = function(){
return $http.get('http://localhost:8080/chartDepense/');
};
return obj;
});
my controller is :
app.controller('myController', function ($scope, $rootScope, ServicesImpl) {
$scope.chart = ServicesImpl.getData().then(function(r){
return r.data;
});
console.log($scope.chart);
$scope.chartOptions = {
title: {
text: $scope.chart.libelle
},
xAxis: {
categories: $scope.chart.categories ,
title: {
text: 'les X'
}
},
yAxis: {
title: {
text: 'les Y'
}
},
series: [{
data: $scope.chart.peroides
}]
};
});
and I got this :
I don't know can I can get my data in my controller to put in chartConfig?
Please give me wher im doing Worng
<div ng-app="customCharts">
<div ng-controller="HelloHell">
</div>
</div>
Angular
var app = angular.module('customCharts', []);
var app = angular.module('customCharts', ['dx']);
app.controller("ChartController", function ($scope, $http, $q) {
$scope.productSettings = {
dataSource: new DevExpress.data.DataSource({
load: function () {
var def = $.Deferred();
$http({
method: 'GET',
url: 'http://localhost:53640/Home/PostChart'
}).success(function (data) {
def.resolve(data);
});
return def.promise();
}
}),
series: {
title: 'Displays Product Costs for items in our Database',
argumentType: String,
argumentField: "Name",
valueField: "Cost",
type: "bar",
color: '#008B8B'
},
commonAxisSettings: {
visible: true,
color: 'black',
width: 2
},
argumentAxis: {
title: 'Items in Product Store Database'
},
valueAxis: {
title: 'Dollor Amount'
}
}
})
Json Controller
public JsonResult PostChart()
{
var prod = new List();
using (Ctxdb db = new Ctxdb())
{
var product = db.Products.ToList();
foreach (var p in product)
{
var thing = new { Name = p.ProductName, Cost = p.Price };
prod.Add(thing);
}
}
return Json(prod, JsonRequestBehavior.AllowGet);
}
Your controller in HTML should be
<div ng-controller="ChartController">
also you should have one module
var app = angular.module('customCharts', []);
I have a route/view that is displaying a blank page. I am pretty sure it was working the way I have it right now a few days ago which leads me to think it is a problem with my Google Maps API key, but there are no errors or warnings so I think it has to do with my routing setup. But I have another view set up exactly the same way and that one does work...
Broken view: http://alainwebdesign.ca/pl2/#/49.2/-122.66
Working view: http://alainwebdesign.ca/pl2/#/getLocation
Controller (I commented out the.config for Google Map API because I have a script reference in my view searchRadius.html) :
(function (window, ng) {
ng.module('app', ['uiGmapgoogle-maps', 'ui.router'])
.config(function ($stateProvider) { //had: , $stateChangeError included in the function parameters, but that caused error
$stateProvider.state('searchRadius', {
url: '/:lat/:lon',
templateUrl: 'searchRadius.html', //changed from index to searchRadius.html
controller: 'MapsCtrl',
});
})
////ALREADY HAVE GOOGLE MAPS KEY ON searchRadius.html
.config(['uiGmapGoogleMapApiProvider', function (GoogleMapApi) {
GoogleMapApi.configure({
key: 'AIzaSyC_XEbbw3sNm4XlLAgqMJTggeHLDUdV-pY',
v: '3',
libraries: 'weather,geometry,visualization'
});
} ])
.controller('MapsCtrl', ['$scope', "uiGmapLogger", "uiGmapGoogleMapApi", "$interval", "$state", "$stateParams",
function ($scope, $log, GoogleMapApi, $interval, $state, $stateParams) {
$log.currentLevel = $log.LEVELS.debug;
var center = { latitude: parseFloat($stateParams.lat), longitude: parseFloat($stateParams.lon) };
alert(JSON.stringify(center));
Object.freeze(center); //caused TypeError: Cannot assign to read only property ('latitude') ...
console.log($stateParams);
$scope.map = {
center: center,
pan: false,
zoom: 16,
refresh: false,
events: {},
bounds: {}
};
$scope.map.circle = {
id: 1,
center: center,
radius: 500, //(current time - date lost)*km/hour
stroke: {
color: '#08B21F',
weight: 2,
opacity: 1
},
fill: {
color: '#08B21F',
opacity: 0.5
},
geodesic: false, // optional: defaults to false
draggable: false, // optional: defaults to false
clickable: true, // optional: defaults to true
editable: false, // optional: defaults to false
visible: true, // optional: defaults to true
events: {
dblclick: function () {
$log.debug("circle dblclick");
},
radius_changed: function (gObject) {
var radius = gObject.getRadius();
$log.debug("circle radius radius_changed " + radius);
}
}
}
//Increase Radius:
$interval(function(){
$scope.map.circle.radius += 30; //dynamic var
}, 1000); //end of interval function
} ]); //end of controller
})(window, angular);
searchRadius.html:
<div style="height: 100%"> <!--took out: ng-if="map.center !== undefined"-->
<ui-gmap-google-map
center='map.center'
zoom='map.zoom'
draggable='map.draggable'
dragging='map.dragging'
refresh='map.refresh'
options='map.options'
events='map.events'
pan='map.pan'>
<ui-gmap-circle
center='map.circle.center'
radius='map.circle.radius'
fill='map.circle.fill'
stroke='map.circle.stroke'
clickable='map.circle.clickable'
draggable='map.circle.draggable'
editable='map.circle.editable'
visible='map.circle.visible'
events='map.circle.events'>
</ui-gmap-circle>
</ui-gmap-google-map>
<script src='//maps.googleapis.com/maps/api/js?key=AIzaSyC_XEbbw3sNm4XlLAgqMJTggeHLDUdV-pY'></script>
</div>
Combine the 2 files into 1 file and initialize the $stateProvider in a single line.
I am using flot chart Angularjs directive to draw a stacked bar chart. When I make a async call to an end point to fetch data for chart, it is unable show up. I suspect it needs to redraw. There is a draw() function which looks like re draws flot chart. Please help me re-draw my flot chart in Angularjs.
<flot dataset="tasksRunData" options="tasksRunChartOptions" class="center-block" width="100%" height="400px" id="reportTasksRunRange.id"></flot>
angular.module('myApp').controller('Step2Controller', function($scope, $location, $interval, dialogs, $modal, $transition, ReportingService) {
...
$scope.tasksRunData = mainArray;
$scope.tasksRunChartOptions = {
legend: {
show: true,
margin: 2
},
xaxis: {
ticks: yaxisArray,
alignTicksWithAxis: "right"
},
grid: {
labelMargin: 10,
hoverable: true,
borderWidth: 0
},
series: {
stack: true
},
colors: colorCodesArray,
tooltip: true
};
...
$scope.redrawTasksRunDataHistoByChart();
...
$scope.redrawTasksRunDataHistoByChart = function() {
$scope.tasksRunData.draw(); //TypeError: undefined is not a function
alert("AAAA");
}
});
Update
ReportService.getTasksRunDateHistoByType().then(function(result) {
$scope.renderTasksRunDateHistoByType(result);
});
$scope.renderTasksRunDateHistoByType = function(jsonInput) {
console.log(json[RUN_AGG_BY_DATE_HISTO].aggregations[TASK_TYPE_AGG].buckets);
var yaxis = [];
var buckets = json[RUN_AGG_BY_DATE_HISTO].aggregations[TASK_TYPE_AGG].buckets;
var log = [];
var mainArray = [];
var colorCodes = ["#5C832F","#7B52AB","#263248","#AB1A25","#FF8598","#AB1A25","#FEB41C","#193441","#193441","#BEEB9F","#E3DB9A","#917A56"],
idx = 0;
angular.forEach(buckets, function(value, key) {
this.push(key + ': ' + value +", "+value["key"]);
var dataArray = [], index = 0;
console.log(JSON.stringify(value[RUN_OVER_TIME_KEY]["buckets"]));
angular.forEach(value[RUN_OVER_TIME_KEY]["buckets"], function(value, key) {
var dataArr = [];
dataArr.push('['+index+', '+value["doc_count"]+']');
dataArray.push(dataArr);
yaxis.push(JSON.parse('['+index+', "'+$scope.translate(value["key"])+'", "'+value["key"]+'"]'));
index++;
}, log);
var barObject = '"bars": {"show": "true", "barWidth":0.8, "fillColor": "'+colorCodes[idx]+'", "order": 1, "align": "center"}';
var object = '{ "data": ['+dataArray+'], "label": "'+value["key"]+'", '+barObject+'}';
mainArray.push(JSON.parse(object));
idx++;
}, log);
console.log(yaxis);
$scope.tasksRunData = mainArray;
$scope.tasksRunChartOptions = {
legend: {
show: true,
margin: 2
},
xaxis: {
//ticks:[[0,'Oct 4'],[1,'Oct 5'],[2,'Oct 6'],[3,'Oct 7'],[4,'Oct 8'],[5,'Oct 9']],
ticks: yaxis,
alignTicksWithAxis: "right"
},
grid: {
labelMargin: 10,
hoverable: true,
borderWidth: 0
},
series: {
stack: true
},
colors: colorCodes,
tooltip: true
};
};
angularjs service
angular.module('myApp')
.service('ReportService', function ReportService($http, $q) {
var getTasksRunDateHistoByType = function() {
var deferred = $q.defer();
$http({
method: 'POST',
url: "http://localhost:4040/reports/taskRun",
data: '{ "client_user_info": { "client_id": "MU03"}}'
}).
success(function(result, status, headers, config) {
deferred.resolve(result);
}).
error(function(result, status, headers, config) {
console.log("Error");
});
return deferred.promise;
};
return {
getTasksRunDateHistoByType: getTasksRunDateHistoByType
};
});
Looking at the source code to the directive, it'll redraw automatically when $scope.dataset changes.
$scope.redrawChart = function() {
var tmp = [];
for (var i = 0; i < 10; i++){
tmp.push([i,Math.random() * 10]);
}
$scope.dataset = [{ data: tmp }];
};
Here's an example.
EDITS FOR UPDATES
I'm having a hard time following your code, but in the end, you'll end up in the $scope.renderTasksRunDateHistoByType with data in the variable jsonInput. You then store some variable mainArray (which doesn't exist as far as I can tell) into other $scope level variables. I never see you assign data back to $scope.dataset. This is what the flot directive is watching to trigger a redraw. It's just that simple.
$scope.renderTasksRunDateHistoByType = function(jsonInput) {
$scope.dataset = [{
data: jsonInput
}];
//console.log(jsonInput);
//$scope.tasksRunData = mainArray;
//$scope.tasksRunChartOptions
//getting data here once response is received from server
};
See updates here.
I'm pretty new to JavaScript & Angular and I'm trying to test this controller but I'm missing something here. Here's the error:
PhantomJS 1.9.7 (Mac OS X) Controller: UserCalendarCtrl Calendar resize based on width resize should call mobile FAILED
spyOn could not find an object to spy upon for width()
user-calendar-controller.spec.js
'use strict';
describe('Controller: UserCalendarCtrl', function() {
var controller,
mockScope,
VivaCalendar;
beforeEach(module('vivaAngularApp', 'ui.calendar'));
beforeEach(inject(function($controller, $rootScope, _VivaCalendar_) {
mockScope = $rootScope.$new();
controller = $controller('UserCalendarCtrl', {
$scope: mockScope
});
VivaCalendar = _VivaCalendar_;
}));
describe('Calendar resize based on width', function() {
it('should set a width', function() {
expect(mockScope.width).toBeDefined(true);
});
describe('resize', function() {
beforeEach(function (mockScope){
spyOn(mockScope, 'width').and.callFake(function(){
return 700;
});
});
it('should call mobile', function() {
expect(mockScope.uiConfig).toEqual(VivaCalendar.uiConfig('mobile'));
});
});
});
describe('event sources', function(){
it('should return event sources', function() {
expect(mockScope.eventSources).toEqual([mockScope.eventSource]);
});
it('should take event source', function(){
expect(mockScope.eventSource.url).toEqual('http://162.243.222.54/fullcalendar/new_fechas_insp.php');
});
});
});
user-calendar-controller.js
'use strict';
app.controller('UserCalendarCtrl', ['$scope', '$window', '$location', 'VivaCalendar', function($scope, $window, VivaCalendar, $location) {
$scope.width = $window.innerWidth;
$scope.$watch('width', function(width) {
if (width < 768) {
$scope.uiConfig = VivaCalendar.uiConfig('mobile');
} else {
$scope.uiConfig = VivaCalendar.uiConfig();
}
});
$scope.eventSource = {
url: 'http://162.243.222.54/fullcalendar/new_fechas_insp.php'
};
$scope.eventSources = [$scope.eventSource];
}]);
viva-calendar.js
'use strict';
app.service('VivaCalendar', function() {
var UiConfig = function(size) {
this.calendar = {
defaultView: 'month',
allDaySlot: false,
minTime: 8,
maxTime: 22,
timeFormat: {
agenda: 'h:mm{ - h:mm}TT'
},
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek'
},
buttonText: {
prev: '‹', // <
next: '›', // >
prevYear: '«', // <<
nextYear: '»', // >>
today: 'Ver el día de hoy',
month: 'mes',
week: 'semana',
day: 'día'
},
columnFormat: {
month: 'ddd', // Mon
week: 'ddd d/M', // 9/7 Mon
day: 'dddd M/d' // 9/7 Monday
},
monthNamesShort: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'Sab'],
dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
editable: false,
hiddenDays: [0, 6]
};
if (size === 'mobile') {
this.calendar.defaultView = 'agendaDay';
this.calendar.header.right = 'month, agendaDay';
}
};
this.uiConfig = function(size) {
return new UiConfig(size);
};
});
The goal of a spy is to replace a function by another one that records the function calls, and potentially does something other than the replaced function.
width here is not a function. It's a simple attribute of type number. So it makes no sense to spy on it. If you want the width of the scope to be 700, you simply need
mockScope.width = 700;