UI-GRID display json data - angularjs

At the moment I am retrieving data from the server.
[
{
id:1,
name:demo,
request: {
id: 1,
localCompany: {
id: 1
}
}
}]
[{ }, { }] so this is how my json object looks.
When I get call the $http service and put it in the gridOptions: {data: this.data}
I get this error in the console window: TypeError: newRawData.forEach is not a function.
data: ng.IPromise<any[]> = this.programService.getRequestsForProgram(this.model.id).then((data: any) => {
console.log(data);
return data;
});
gridOptions: {} = {
data: this.data ,
paginationPageSize: 5
//columnDefs: this.programCountryService.getHeaders()
};
This is the code I am using at the moment.
Any idea how I can get rid of this error? And is it possible that the grid only shows localCompany.Id and not the name:demo?

Try to put the data in $scope.data
Like $scope.data=getdata from server
and then
gridOptions: {} = {
data: $scope.data ,
paginationPageSize: 5
//columnDefs: this.programCountryService.getHeaders()
};

Put data into $scope and than to gridOptions.data = $scope.data.
If you want to show only data for localCompany.id you need to make definition for columnDefs for field request with custom template like:
'<div class="ui-grid-cell-contents">{{ COL_FIELD.id }}</div>'

Related

Set selected value in Select2 using angularjs

I have a Drop down in my Anjularjs Application implemented using 'ui.select2'
I had initialized it as below
<input type="text" ng-model="objCas.iProjectId" id=" iprojectid" ui-select2="iProjectIdOption" />
And My Js Implementation is getting data from remote server with pagination and filter
var app = angular.module('CASApp', ['ui.select2', 'checklist-model']);
app.controller('CASController', function ($scope, $http) {
$scope.iProjectIdOption = {
placeholder: "Click to choose the Project...",
allowClear: true,
initSelection: function (element, callback) {
},
ajax: {
url: "/Prj/dummy/Ajaxlist",
quietMillis: 0,
type: "POST",
data: function (term, page) {
return {
q: term,
page: page,
listType: "ProjectDetails"
}; // query params go here
},
results: function (data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
var more = (page * 30) < data.total_count; // whether or not there are more results available
return {
results: $.map(data.items, function (item) {
return {
text: item.text,
id: item.id
}
}),
more: more
}
},
cache: true
}
}
}
}
Everything works fine .I am able to use all the features and post the values also. But problem is with setting the already selected values at time of edit
Tried
$Scope.objCas.iProjectId= {"text":"2010 / 256 - / dummytext","id":240}
$Scope.objCas.iProjectId=2;
$scope.iProjectId.selected = {"text":"2010 / 256 - / dummytext","id":240}
Get the select2 element object and apply the following code:
angular.element("#select2_id").select2('data', { "text": "text", "id": [id]});
HTML code: no need of id
<input type="text" ng-model="objCas.iProjectId" ui-select2="iProjectIdOption" />
js code:
use only this for default biniding
$Scope.objCas.iProjectId= {"text":"2010 / 256 - / dummytext","id":240}
example code:
link: http://embed.plnkr.co/K66Pf0/
replace script.js file:
// Code goes here
var myAppModule = angular.module('MyApp', ['ui.select2']);
myAppModule.controller('MyController', function($scope) {
$scope.select2Options = {
initSelection: function (element, callback) {
},
ajax: {
url: "./data.json",
data: function (term, page) {
return {}; // query params go here
},
results: function (data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return {results: data}
}
}
}
console.log("$scope.select2Options-",$scope.select2Options.initSelection);
$scope.testModel={ "id": 4, "text": "Fourth", "color": "red" }
;
});
you can view default selected value in dropdown.

Highchart is not working when I am fetching the axis values from database

I am using ASP .Net web api to fetch the data from the database, And trying to make a graph of the derived data , using Highchart. When I am giving the axis values in the form:
xAxis: {
categories:["Sabab","Sunjare","Ety"]
},
series: [{
data: [20,30,40]
}]
it is working fine. But when I am initializing the categories of xAxis and data of series , by the data , derived from the database, no graph is formed then.
Here is the angular controller code.
app.controller('chartController', function ($scope,chartService) {
loadStudentName();
function loadStudentName() {
var promiseget = chartService.getStudentName();
promiseget.then(function (p1) { $scope.StudentNames = p1.data },
function (errorP1) {
alert("Error Occurred");
});
}
loadTotalMarks();
function loadTotalMarks() {
var promiseget = chartService.getTotalMarks();
promiseget.then(function (p1) { $scope.TotalMarks = p1.data },
function (errorP1) {
alert("Error occured");
}
);
}
Highcharts.chart('container', {
chart: {
type: 'column'
},
xAxis: {
categories:$scope.StudentNames
},
yAxis: {
title: {
text:"Marks"
},
},
series: [{
name: "Marks",
data: $scope.TotalMarks
}]
});
});
The $scope.StudentNames is populated with ["Ety","Sabab","Sunjare","Sadia"] from the database and $scope.TotalMarks is populated with [393,390,394,341] from the database, but yet the graph is not formed.
You need to refresh your highcharts after data is updated, either:
put a watch on both of your data objects and do chart.redraw(); if
it changes
call redraw method after after you update your data
inside of promise.
I recommend creating a directive that takes highchart config object and watches that for changes and then redraws the chart, that way you can reuse it.

How to push json data into array in angular js

How do i get data in $scope.moduleSelected into label in the treedata_avm array instead of the hardcoded values present in the array?
app.controller('treeController',['$http','$scope','dataService',function( $http,$scope,dataService){
$http.get('WS/tree').success(function(data,status){
$scope.modules=data;
$scope.moduleSelected = $scope.modules[0].MODULE_NAME;
$scope.moduleSelectedId = $scope.modules[0].ID;
$scope.moduleSelectedParentId = $scope.modules[0].PARENT_ID;
console.log($scope.modules);
console.log($scope.moduleSelected);
console.log($scope.moduleSelectedId);
console.log($scope.moduleSelectedParentId);
}).error(function(data){
$scope.modules=data || "Request failed";
console.log("Request failed "+ $scope.modules);
});
}]);
treedata_avm:
treedata_avm = [
{
label: 'Animal',
children: [
{
label: 'Dog',
}, {
label: 'Cat',
}, {
label: 'Hippopotamus',
}, {
label: 'Chicken',
children: ['White Leghorn', 'Rhode Island Red', 'Jersey Giant']
}
]
}]
You can listen to event 'onchange' on the field, that's bound to $scope.moduleSelected and change your json when input field is changed. But I can't see, why would you need something like this?
$http with its success promise resolve function returns data in the current format: response.data
Meaning in your case you should first set
$http.get('WS/tree').success(function(response){
$scope.modules = response.data;
$scope.treedata_avm = response.data
}).error(function (){...})
If you are going to use your treedata_avm on a view, then it should be on the $scope as in $scope.treedata_avm if not then just use it as a variable inside the controller
Also my advice would be to put all of this $http logic into a provider (factory, service, provider) and then invoke it from there.
The advice is to make controllers as thin as possible and put the logic inside the providers (factories, services, providers), thus making it reausable
Hope this helps.

Angular and MEAN.js $scope attributes are undefined

I am currently developing a little app with Angular and MEAN.js.
I would like to plot a D3 chart with some real data coming from the model.
To do so, I would have to read from the $scope.campaign variable and initialize the $scope.dataBarChart with the data from $scope.campaign.tokens that is an array.
// Find existing Campaign
$scope.findOne = function() {
$scope.campaign = Campaigns.get({
campaignId: $stateParams.campaignId
});
$scope.dataBarChart = [
{
'key': 'Token Requested',
'values': [['10.10.2014', 550000], ['11.10.2014',300000]]
}, {
'key': 'Token Consumed',
'values': [['10.10.2014', 250000], ['11.10.2014',200000]]
}
];
};
When I try to log the value of $scope.campaign, I get all the data that I need. Unfortunately, when I try to access the $scope.campaign.tokens, I get an error like impossible to access tokens from undefined value. Basically, it seems that there is no data, but I know from the log that is not like this.
The complete code is simply the same, but with a console.log line
// Find existing Campaign
$scope.findOne = function() {
$scope.campaign = Campaigns.get({
campaignId: $stateParams.campaignId
});
console.log($scope.campaign)
$scope.dataBarChart = [{
'key': 'Token Requested',
'values': [['10.10.2014', 550000], ['11.10.2014',300000]]
}, {
'key': 'Token Consumed',
'values': [['10.10.2014', 250000], ['11.10.2014',200000]]
}];
};
The console.log shows the right content, but when I try to use it $scope.campaign.tokens, it says undefined.
Anyone suggestions?
Thanks
Try
$scope.campaign.$promise.then(function(data) {
console.log(data.tokens)
});

Angular JS: JSON data is not getting displayed in ng-Grid

I have created MVC 4.0 app using Web API which returns data in JSON format (I am serializing object to json using NewtonSoft.Json) and trying to bind data in ng-Grid. I am receiving data in following format:
"[{\"Name\":\"FIRST_NAME\",\"Value\":\"FIRST_NAME\"},{\"Name\":\"CURRENT_DATE_TIME\",\"Value\":\"CURRENT_DATE_TIME\"},{\"Name\":\"CLIENTID\",\"Value\":\"CLIENTID\"},{\"Name\":\"CALLMODE\",\"Value\":\"CALLMODE\"}, {\"Name\":\"new 321\",\"Value\":null}]"
When i tried to assign same to data: of ng-Grid, each char populated on different row. following is the javascript i have written:
var guidesRespApp = angular.module('guidesRespApp', ['ngGrid']);
//Get Data from restful API.
guidesRespApp.controller('MyCtrl', function ($scope, $http) {
$http.get('/api/datadictionary').success(function (thisdata) {
$scope.myData = thisdata;
});
$scope.filterOptions = {
filterText: '',
useExternalFilter: true,
};
//Setting grid options
$scope.gridOptions = {
data: 'myData',
multiSelect: true,
filterOptions: { filterText: '', useExternalFilter: false },
enableRowReordering: false,
showGroupPanel: false,
maintainColumnRatios: false,
groups: [],
showSelectionCheckbox: true,
showFooter: true,
enableColumnResize: true,
enableColumnReordering: true
};
// $scope.totalFilteredItemsLength = function() {
// //return self.filteredRows.length;
// };
});
If manually assigned like below, data is getting displayed in grid:
$scope.myData = [{"Name":"FIRST_NAME","Value":"FIRST_NAME"},{"Name":"CURRENT_DATE_TIME","Value":"CURRENT_DATE_TIME"},{"Name":"CLIENTID","Value":"CLIENTID"},{"Name":"CALLMODE","Value":"CALLMODE"}];
can anyone please help me to understand how to fix it?
Also i wanted to display count of filtered items when i key in values in filtertext.
As mentioned on http://angular-ui.github.io/ng-grid/ , Data being displayed in the grid is of type array and each element in that array mapped to a row being displayed. So I modified my code like below and it worked for me:
$http.get('http://localhost:12143/api/datadictionary').success(function (thisdata) {
//Convert data to array.
var myData = $.parseJSON(JSON.parse(thisdata));
$scope.myData = myData;
});
even var myData = $.parseJSON(angular.fromJson(thisdata)); also working. Just we need first to parse the data (for this I used JSON.parse()) and then convert to array (for this i used $.parseJSON()).
Try changing the get callback to one of the following:
$http.get('/api/datadictionary').success(function (thisdata) {
$scope.myData = JSON.parse(thisdata);
// or
$scope.myData = angular.fromJson(thisdata);
});
Reference this with regards to how webapi is returning json. ASP.NET WebAPI: How to control string content returned to client?

Resources