I am using Chart Js and Angular Chart Directive. I need bar chart dynamically in my ng-repeat directive.
https://jtblin.github.io/angular-chart.js/
According to their documentation i have to give two arrays
$scope.labels = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
$scope.data = [
[65, 59, 80, 81, 56, 55, 40]
];
I have made two functions in my controller for generating graph label and data array.
$scope.makeChartLbl=function(data)
{
console.log(data);
var arr=[];
for(var d in data)
{
arr.push(d.name)
}
// console.log(arr);
return arr;
}
$scope.makeChartData=function(data)
{
console.log(data);
var arr=[];
for(var d in data)
{
arr.push(d.total_vote)
}
// console.log(arr);
return arr;
}
My options object in dataset like as
{
"options": [
{
"id": 1,
"pool_id": 1,
"name": "pool1 option1",
"total_vote": 1
},
{
"id": 2,
"pool_id": 1,
"name": "pool1 option2",
"total_vote": 0
},
...
...
]
}
In view with ng-repeat directive
<canvas id="bar" class="chart chart-bar"
chart-data="makeChartData(options)" chart-labels="makeChartLbl(options)">
</canvas>
but it is not generating chart. How can solve this issue?
There are multiple issues :
I am not sure you are reading your Object correctly, check the code for my implementation; The other issue is that Angular trows a $rootScope:infdig error due to how you are creating new arrays inside your functions, I fixed that as well, but you might need to modify it for your particular case.
This is one solution:
var chartData = [];
var chartLabels = [];
$scope.options = options;
$scope.makeChartLbl = function(data) {
chartData.length = 0;
data.forEach(function(datum) {
chartData.push(datum.name);
});
return chartData;
}
$scope.makeChartData = function(data) {
chartLabels.length = 0;
data.forEach(function(datum) {
chartLabels.push(datum.total_vote);
});
return chartLabels;
}
}]);
var options = [
{
"id": 1,
"pool_id": 1,
"name": "pool1 option1",
"total_vote": 1
},
{
"id": 2,
"pool_id": 1,
"name": "pool1 option2",
"total_vote": 0
}
];
Full code in codepen:
Angular Chart.js issue
Result:
Related
New to AngularJS so apologies if my terminology isn't correct. I am trying to call a value that is in my JSON body, however the difference is that it's also inside another body called student.
{
"id": 3,
"teacherName": "N/A",
"students": [
{
"student": "n/a"
}
],
"status": "ALIVE"
}
My JS code consists of the following:
$scope.table = function () {
SpringDataRestService.get(
{
collection: "school",
resource: $scope.teacherSelected.id
},
function (response) {
var students= [];
for (var j = 0; j < response.students.length; j++) {
var entitlement= {
student: response[j].student,
};
students.push(entitlement);
}
$log.info(JSON.stringify(entitlement))
$scope.tableOptions = new NgTableParams({}, {
dataset: students,
counts: []
});
}
);
};
There is an error in for loop. Instead of:
student: response[j].student
you need to use this:
student: response.students[j].student
Check this working demo: DEMO
I would like to compare JSON values to an array of values but I d'ont know what's the best scenario to go with.
I got a JSON object with expected values (could have 1 value , 2 or more)
I have a DB function that returns a fix number of values, say 10 values all the time and I would like to know if my JSON values matches the right one coming from DB.
Ex:
My JSON var is :
var expValues = {
"id": "123",
"age": 23
};
My DB will push some values to an Array of objects.
Ex:
if ((rs.BOF) && (rs.EOF))
{
//nothing found;
}
else
{
while (!rs.EOF)
{
aDetails.push(
{
"id": rs.fields("id").Value,
"name": rs.fields("name").Value,
"age": rs.fields("age").Value,
"sex": rs.fields("sex").Value,
"hobby": rs.fields("hobby").Value
});
rs.MoveNext();
}
}
rs.close;
//Close connection then return
return aDetails;
basically I want to make sure values coming from JSON match the right ones coming from DB. (id for example).
I have assumed aDetails to have something like below data.
let aDetails = [{
"id": "123",
"name": "as",
"age": 23,
"sex": "m",
"hobby": "abc"
}, {
"id": "1234",
"name": "as1",
"age": 23,
"sex": "m",
"hobby": "abc"
}, {
"id": "12",
"name": "as2",
"age": 23,
"sex": "m",
"hobby": "abc"
}]
var expValues = {
"id": "123",
"age": 23
};
function isObjectMatched(obj) {
return aDetails.some(d => Object.entries(obj).every(([k, v]) => d[k] == v))
}
console.log(isObjectMatched(expValues))
This is a general purpose way of indexing list of objects for fast retrieval with any configuration of properties.
// javascript version
function makeIndex (arrayOfObject, listOfPropertyToIndex) {
var index = {};
index.objToKey = function (o) {
var key = [];
listOfPropertyToIndex.forEach((p) => {
key.push(""+o[p]);
});
return key.join("_");
};
arrayOfObject.forEach((o) => {
index[objToKey(o)] = o;
});
index.match = function (object) {
var key = index.objToKey(object);
if (index.hasOwnProperty(key)) {
return index[key];
};
return null;
});
return index;
}
// jscript version
function makeIndex (arrayOfObject, listOfPropertyToIndex) {
var index = {};
index.objToKey = function (o) {
var key = [];
for (var p in o) {
if (o.hasOwnProperty(p)) {
key.push(""+o[p]);
}
}
return key.join("_");
};
for (var i = 0; i < arrayOfObject.length; ++i) {
index[objToKey(arrayOfObject[i])] = o;
}
index.match = function (object) {
var key = index.objToKey(object);
if (index.hasOwnProperty(key)) {
return index[key];
};
return null;
});
return index;
}
Here is how to use it
var expValues = {
"id": "123",
"age": 23
};
var index = makeIndex(aDetails, ["id","age"]);
var obj = index.match(expValues);
if (obj) {
... obj ...
}
var index_name = makeIndex(aDetails, ["name"]);
var person = {"name":"as2"};
var obj2 = index_name.match(person);
if (obj2) {
... obj2 ...
}
i want to get the maximum and minimum value from a json in angular js
my json:
{
"data":[
{
"name": "ranjith",
"age": 22
},
{
"name": "rahul",
"age": 20
},
{
"name": "jinesh",
"age": 25
},
{
"name": "vishnu",
"age": 24
}
]
}
and my controller:-
var app = angular.module('myApp', ['']);
app.controller('myCtrl', function($scope, data) {
$scope.data = data.data;
$scope.min="";
$scope.max="";
};
});
i want to get the minimum and maximum value from the array and store it in the Variables min and max
You can simply use
$scope.min = Math.min.apply(Math,$scope.data.map(function(item){return item.age;}));
$scope.max = Math.max.apply(Math,$scope.data.map(function(item){return item.age;}));
To avoid using 3rd party lib
for (var index in $scope.data.data)
{
var item=$scope.data.data[index];
if($scope.min==0 && $scope.max==0){
// set first default element
$scope.min=item.age;
$scope.max=item.age;
}
else{
if($scope.min>item.age)
$scope.min=item.age;
else if($scope.max<item.age)
$scope.max=item.age;
}
}
You can use Underscore.js with angular and then in your controller,
var ageArr = _.pluck(data.data, 'age');
$scope.min= _.min(ageArr);
$scope.max= _.max(ageArr);
Plunker url http://run.plnkr.co/plunks/Mw531cqUIHVSorb5kOac/
1.Add Underscore dependency
2.Use the following:
//For Maximum Age:
_.max(data, function(itr){ return itr.age; });
/* O/p = {
"name": "jinesh",
"age": 25
}*/
//For Minimum Age:
_.min(data, function(itr){ return itr.age; });
/* O/p = {
"name": "rahul",
"age": 20
} */
If the intent is to display, you can directly arrive at min by this:
{{(data | orderBy:'age')[0].age}}
I am using FiltersFeature:
this.features = {
ftype: 'filters',
encode: false,
local: true
};
I would like to access my current filters on my table. Ie. not the filter configuration object, but what the changes user has done to the table (I want to save this in the database).
There is a filters object on grid, but that just gives me the filter configuration from all the columns.
handler: function (btn) {
var grid = btn.up('grid');
grid.filters
}
I need the actual values. I'm looking for something like this:
var v = {
filter: {
column: 'name',
value: 'bob'
},
filter: {
column: 'date',
value1: '11.11.11',
value2: '12.12.12'
}
}
Anyone know where i can get this info?
The answer I found out was to use this method :)
myTableGrid.filters.getFilterData()
I get something like this :
v = [{
"field": "myColumn1",
"data": {
"type": "string",
"value": "anna"}
}, {
"field": "myColumn2_fixedvalue",
"data": {
"type": "list",
"value": [60]}
}]
Filter does not contain any values.
You should parse actual values from the grid.
var columnTitle = [];
var fieldName = [];
var data = [];
var visibleColumns = grid.query('gridcolumn:not([hidden])');
visibleColumns.forEach(function(c) {
columnTitle.push(c.text);
fieldName.push(c.dataIndex);
});
for (rowIndex = 0; rowIndex < grid.store.getCount(); rowIndex++) {
var row = grid.getView().getRow(rowIndex);
var fieldValues = Ext.fly(row).query('div.x-grid-cell-inner');
var map = {}
for (colIndex = 0; colIndex < fieldName.length; colIndex++) {
map[fieldName[colIndex]] = fieldValues[colIndex].textContent;
}
data.push(map);
}
As a result, you will get an array of objects, something like
[{"user.login":"iivanov","email":"ivanov#mail.com"},{"user.login":"ppetrov","email":"petrov#mail.com"},{"user.login":"plosev","email":"elk#gmail.com"}]
I have a code as follow:
function getdata($scope){
$scope.todos = [
{name:"john",data:"1 2 3"},
{name:"Marry",data:"6 7 8"},
{name:"Edward",data:"2 4 5"}
];
var seri=new Array();
for(var item in $scope.todos)
{
seri.push(
{
name: item.name,
data: [1, 0, 4]
});
}
console.log(seri);
}
Now when I check the console for the name it returns undefined. what is the problem?
Try
function getdata($scope) {
$scope.todos = [
{ name: "john", data: "1 2 3" },
{ name: "Marry", data: "6 7 8" },
{ name: "Edward", data: "2 4 5" }
];
var seri = new Array();
angular.forEach($scope.todos, function (item, key) {
seri.push({
name: item.name,
data: [1, 0, 4]
});
});
console.log(seri);
//you can get data from this by using return
}
When you loop through an array in javascript the item is an integer with the position of the value in the array. You'll need to use this position to get the true item, like this:
for (var i in $scope.todos) {
var item = $scope.todos[i];
...
}
If the function is inside a controller and being called as such you should declare it as
$scope.getData = function() {
}
And then it should work fine. If the function is NOT to be part of the scope and you are passing the scope in then try receiving the parameter as "scope" and not "$scope" which has a special meaning in Angular.
this is not how you iterate array in javascript (see materik answer).
you can alternatively use angular.forEach to iterate the todos array like this:
angular.forEach($scope.todos, function(item)
{
seri.push(
{
name: item.name,
data: [1, 0, 4]
});
});