I am using ng-table for AngularJS and i am using single JSON file for the table data. i want to import multiple JSON files into a single table. I am able to import single JSON file using this code below.
Thank you in advance.
HTML
<table ng-table="tableParams" show-filter="true" class="table ng-table-responsive">
<tr ng-repeat="user in $data">
<td data-title="'ID'" sortable="'ID'">
{{user.ID}}
</td>
<td data-title="'Name'" sortable="'Name'" filter="{ 'name': 'Name' }">
{{user.Name}}
</td>
<td data-title="'Email'" sortable="'email'">
{{user.email}}
</td>
<td data-title="'Address'" sortable="'address'">
{{user.address}}
</td>
<td data-title="'PersonalEmail'" sortable="'personalemail'">
{{user.personalemail}}
</td>
<td data-title="'PhoneNo'" sortable="'phoneno'">
{{user.phoneno}}
</td>
<td data-title="'Status'" sortable="'status'">
{{user.status}}
</td>
</tr>
</table>
JavaScript
var app = angular.module('main', ['ngTable']).controller('DemoCtrl', function($scope, ngTableParams, NameService) {
var data = NameService.data;
$scope.tableParams = new ngTableParams(
{
page: 1, // show first page
count: 10, // count per page
sorting: {name:'asc'}
},
{
total: 0, // length of data
getData: function($defer, params) {
NameService.getData($defer,params,$scope.filter);
}
});
$scope.$watch("filter.$", function () {
$scope.tableParams.reload();
});
});
app.service("NameService", function($http, $filter){
function filterData(data, filter){
return $filter('filter')(data, filter)
}
function orderData(data, params){
return params.sorting() ? $filter('orderBy')(data, params.orderBy()) : filteredData;
}
function sliceData(data, params){
return data.slice((params.page() - 1) * params.count(), params.page() * params.count())
}
function transformData(data,filter,params){
return sliceData( orderData( filterData(data,filter), params ), params);
}
var service = {
cachedData:[],
getData:function($defer, params, filter){
if(service.cachedData.length>0){
console.log("using cached data")
var filteredData = filterData(service.cachedData,filter);
var transformedData = sliceData(orderData(filteredData,params),params);
params.total(filteredData.length)
$defer.resolve(transformedData);
}
else{
console.log("fetching data")
$http.get("json/1.json").success(function(resp)
{
angular.copy(resp,service.cachedData)
params.total(resp.length)
var filteredData = $filter('filter')(resp, filter);
var transformedData = transformData(resp,filter,params)
$defer.resolve(transformedData);
});
}
}
};
return service;
});
Retrieve all your JSON content with $q.all() and merge your arrays in the callback. Finally pass the resulting array to ng-table.
Related
In the readme of Angular module "md-data-table" it says "Assume we have a $nutrition service". I tried adding a service (makerService), with a return of data. But I can't see the data represented on the screen. I tried different JSON formats, as an error I get:
$makerService.makers.get is not a function
This is my Javascript code:
(function() {
'use strict';
angular.module('BowbleCRM', [
'ngMaterial',
'md.data.table'
])
.service('$makerService', function () {
var makers = {
"makers" : [
{"full_name": "Jan", "email": "jan#test.nl"},
{"full_name": "Pieter", "email": "pieter#test.nl"}
]
};
return makers;
})
.controller('BowbleCRMController', ['$makerService', '$scope', BowbleCRMController]);
function BowbleCRMController($makerService, $scope) {
'use strict';
$scope.currentNav = 'importeren';
$scope.selected = [];
$scope.query = {
order: 'full_name',
limit: 5,
page: 1
};
function success(makers) {
console.log(makers);
$scope.makers = makers;
}
$scope.getMakers = function () {
$scope.promise = $makerService.makers.get($scope.query, success).$promise;
};
}
})();
And this is a part of my HTML.
<md-toolbar class="md-table-toolbar md-default">
<div class="md-toolbar-tools">
<span>Alle makers</span>
</div>
</md-toolbar>
<!-- exact table from live demo -->
<md-table-container>
<table md-table md-row-select multiple ng-model="selected" md-progress="promise">
<thead md-head md-order="query.order" md-on-reorder="getMakers">
<tr md-row>
<th md-column><span>Volledige naam</span></th>
<th md-column><span>E-Mail adres</span></th>
</tr>
</thead>
<tbody md-body>
<tr md-row md-select="maker" md-select-id="full_name" md-auto-select ng-repeat="maker in makers.data">
<td md-cell>{{maker.full_name}}</td>
<td md-cell>{{maker.email}}</td>
</tr>
</tbody>
</table>
</md-table-container>
<md-table-pagination md-limit="query.limit" md-limit-options="[5, 10, 15]" md-page="query.page" md-total="{{makers.length}}" md-on-paginate="getMakers" md-page-select></md-table-pagination>
How can I make a correct service, and showing the data with the Angular module "md-data-table"?
You don't have a function get on $makerService, you just return makers which is an object.
If you want to call a get promise you must implement it on makerService. Something like
.service('$makerService', function () {
var makers = {
"makers" : [
{"full_name": "Jan", "email": "jan#test.nl"},
{"full_name": "Pieter", "email": "pieter#test.nl"}
]
};
function get(params){
//..implement your logic here (for your controller code, this should return a promise)
}
return {
makers: makers,
get: get
};
})
And in your controller you can call it like this:
$scope.getMakers = function () {
$scope.promise = $makerService.get($scope.query, success).$promise;
};
I try to put data from another array into one part in table.
My first json "names" :
[
{
"name": "AAAAAA",
"down": "False"
},
{
"name": "BBBBBB",
"down": "True"
},
{
"name": "CCCCC",
"down": "False"
}
]
Second json "data" :
[
{
"data": "35%"
}
]
Javascript:
var app = angular.module('app', []);
app.service('service', function($http, $q){
this.getNames = function () {
var names = $http.get('names.json', {cache: false});
var datas = $http.get('data.json', {cache: false});
return $q.all({datas,names});
};
});
app.controller('FirstCtrl', function($scope, service, $http) {
var promise = service.getNames();
promise.then(function (data) {
$scope.names = data.names.data;
$scope.datas = data.datas.data;
$scope.namesanddata = $scope.names.concat($scope.datas);
console.log($scope.namesplit);
console.log($scope.datas);
});
});
Table in HTML :
div ng-controller="FirstCtrl"
<table>
<tbody>
<tr ng-repeat="name in namesanddata">
<td>{{name.name}}</td>
<td ng-if="name.down=== 'False'">{{name.down}}</td>
<td ng-if="name.down !== 'False'">{{name.data}}</td>
</tr>
</tbody>
</table>
</div>
My problem - <td ng-if="name.down !== 'False'">{{name.data}}</td>dont show in table. in console.log it concat to array like 4 object and probably by this it don't show in table next to {{name.name}}, but i don't know how to show {{name.data}} from another json in table instead {{name.down}}.
Thanks for answers in advance.
To give you an output of:
AAAAAA False
BBBBBB 35%
CCCCC False
Remove this line from the Controller:
$scope.namesanddata = $scope.names.concat($scope.datas);
Then either:
Solution 1 - Inline in the view
Change your ng-repeat as follows:
<tr ng-repeat="name in names">
<td>{{ name.name }}</td>
<td>{{ (name.down === 'False') ? name.down : datas[0].data }}</td>
</tr>
OR
Solution 2 - Keep the view clean by using a Filter
app.filter('myFilter', function () {
return function(items, datas) {
var filtered = [];
angular.forEach(items, function (i) {
if (i.down !== "False")
i.down = datas[0].data;
filtered.push(i);
});
return filtered;
}
});
Change your ng-repeat as follows:
<tr ng-repeat="name in names | myFilter: datas">
<td>{{ name.name }}</td>
<td>{{ name.down }}</td>
</tr>
what I am trying to do
I am trying to make one of my columns to take two number (in one column), so I can filter the numeric data by range just for this column. All other sort and pagination and filter by 'contain text' is working fine but I am just not sure how would I go about making just one particular column to have 'range' filter.
graphical representation of what I want
column_header1 columns_header2 column_header3
contain_filter1 contain_filter2 filter3_min_number
filter3_max_number
data data numeric data
. . .
. . .
. . .
What I have so far
I found one example from ng-table module website and I tried to implement their code to mine but I don't know how to approach it when I have to implement the range function inside my 'getData'.
Example that I found http://codepen.io/christianacca/pen/yNWeOP
The custom filter algorithm on 'age' data was what I was looking at.
my app.js
$http.get("http://hostname:port/variant/whole/1-10000", {cache: true})
.then(function (response) {
$scope.variants = response.data;
$scope.data = $scope.variants;
var self = this;
self.variantFilterDef = {
start: {
id: 'number',
placeholder: 'Start'
},
end: {
id: 'number',
placeholder: 'End'
}
};
self.variantsTable = new NgTableParams({
page:1,
count: 10
}, {
filterOptions: { filterFn: variantRangeFilter },
dataset: $scope.data,
filterLayout: "horizontal"
});
function variantRangeFilter(data, filterValues/*, comparator*/){
return data.filter(function(item){
var start = filterValues.start == null ? Number.MIN_VALUE : filterValues.start;
var end = filterValues.end == null ? Number.MAX_VALUE : filterValues.end;
return start <= item.pos && end >= item.pos;
});
}
/* from this part on, it is working code but no 'Range' function
$scope.variantsTable = new NgTableParams({
page: 1,
count: 10
}, {
total: $scope.variants.length,
getData: function (params) {
if (params.sorting()) {
$scope.data = $filter('orderBy')($scope.variants, params.orderBy());
} else {
$scope.data = $scope.variants;
}
if (params.filter()) {
$scope.data = $filter('filter')($scope.data, params.filter());
} else {
$scope.data = $scope.data;
}
$scope.data = $scope.data.slice((params.page() - 1) * params.count(), params.page() * params.count());
return $scope.data;
}
});
*/
});
});
my variant.html
<table ng-table="variantsTable" show-filter="true" class="table table-bordered table-striped table-condensed">
<tr ng-repeat="variant in $data">
<td data-title="'chrom'" sortable="'chrom'" filter="{ 'chrom': 'text' }" >
{{variant.chrom}}
</td>
<td data-title="'id'" sortable="'id'" filter="{ 'id': 'text' }" >
{{variant.id}}
</td>
<td data-title="'pos'" sortable = "'pos'" filter = "{ 'pos': 'text' }">
{{variant.pos}}
</td>
I would really appreciate any suggestion or any input, thanks!
The filter attribute of the ID table cell is not correct.
<td data-title="'id'" sortable="'id'" filter="{ 'id': 'text' }">
{{variant.id}}
</td>
Change it to:
<td data-title="'id'" sortable="'id'" filter="variantFilterDef">
{{variant.id}}
</td>
EDIT
After a bit of trial and error I have it working. I started from your code sample and made a number of changes. I used ControllerAs syntax. But essentially the fixes are:
<td data-title="'chrom'" sortable="'chrom'" filter="{ 'chrom': 'text' }">
to <td data-title="'chrom'" sortable="'chrom'" filter="{ 'name': 'text' }">
<td data-title="'pos'" sortable = "'pos'" filter = "{ 'pos': 'text' }">
to <td data-title="'pos'" sortable="'pos'" filter="variantCtrl.variantFilterDef">
if (params.filter()) {
self.data = $filter('filter')(self.data, {name: params.filter().name});
self.data = variantRangeFilter(self.data, params.filter());
} else {
self.data = self.data;
}
The main issue was the need to separate out the filters of the two columns in #3 by using {name: params.filter().name}) & then calling the custom Pos filter separately.
Codepen: http://codepen.io/anon/pen/QKBYOq?editors=1011
I use this function de read data from a web service
$scope.getProduitByCatID = function () {
$http.get("/getProduitByCategorieID?id=" + $scope.categorie.id).success(function (data) {
$scope.produits = data;
});
};
the value in my model $scope.produits is :
{
"reference": 1,
"designation": "sony",
"prix": 5100,
"categorie": {
"id": 1,
"nom": "serveur"
}
}
I want to show this result with an ng-repeat
<tr ng-repeat="p in produits">
<td>{{p.reference}}</td>
<td>{{p.designation}}</td>
<td>{{p.prix}}</td>
</tr>
but it's not work
I want to extract just this information in my model :
{
"reference": 1,
"designation": "sony",
"prix": 5100
}
because I have two entities product(id,designation,prix) and categorie(id,nom) in association ManytoOne how I can do that using angularJS?
$scope.produits has to be an array. And every time you receive new data, you push it into this array:
$scope.produits = [];
$scope.getProduitByCatID = function () {
$http.get("/getProduitByCategorieID?id=" + $scope.categorie.id)
.then(function successCb(res) {
$scope.produits.push(res.data);
}, function errorCb() {
})
;
};
Or you create a new array every time you receive new data:
$scope.getProduitByCatID = function () {
$http.get("/getProduitByCategorieID?id=" + $scope.categorie.id)
.then(function successCb(res) {
$scope.produits = [res.data];
}, function errorCb() {
})
;
};
Or you can even create an array in ngRepeat:
<tr ng-repeat="p in [produits]">
You can do like this
Declare array scope $scope.produits=[].
$scope.getProduitByCatID=function(){
$http.get("/getProduitByCategorieID?id="+$scope.categorie.id)
.success(function(data){
$scope.produits.push(data) ;
});
};
Create then html from produits array.
<tr ng-repeat="p in produits">
<td>{{p.reference}}</td>
<td>{{p.designation}}</td>
<td>{{p.prix}}</td>
<td valign="top">
<table>
<tr ng-repeat="c in p.categorie">
<td>{{c.id}}</td>
<td>{{c.nom}}</td>
</tr>
</table>
</td>
</tr>
Since you said you have a JSON string, you can use
$scope.produits=JSON.parse(data) to get the Object from the JSON string. As
the others said, to use it in ngRepeat, it has to be an array:
Example without ng-repeat
$http.get("/getProduitByCategorieID?id="+$scope.categorie.id)
.success(function(data){
$scope.produits=JSON.parse(data);
});
Then:
<tr">
<td>{{produits.reference}}</td>
<td>{{produits.designation}}</td>
<td>{{produits.prix}}</td>
</tr>
To use ng-repeat, your JSON string needs to be like this:
[{"reference":1,"designation":"sony","prix":5100.0,"categorie":{"id":1,"nom":"serveur"}}]
But you don't need it, to get just reference, destignation and prix
As your data is an object:
{
"reference": 1,
"designation": "sony",
"prix": 5100,
"categorie": {
"id": 1,
"nom": "serveur"
}
}
You can show it in the view, by this way:
<table border="1">
<tbody>
<tr>
<td>{{produits.reference}}</td>
<td>{{produits.designation}}</td>
<td>{{produits.prix}}</td>
</tr>
<!-- To show categorie data. -->
<tr>
<td colspan="3">
<table border="1">
<thead>
<tr>
<td colspan="2">categorie</td>
</tr>
</thead>
<tbody>
<tr>
<td>id:</td>
<td>{{produits.categorie.id}}</td>
</tr>
<tr>
<td>nom:</td>
<td>{{produits.categorie.nom}}</td>
</tr>
</tbody>
</table>
</td>
</tr>
<!-- End to show categorie data. -->
</tbody>
</table>
I am studying Angular and I have a problem with my code. I am trying to create an ajax request by using promise and service. My output in ajax access in successful but I can't display it in the view.
Here's some of my code:
<div ng-app="promiseCall">
<div ng-controller="promiseCtrl">
<button tyle="button" class="btn btn-default" ng-click="promiseCallRequest()">Promise Call</button>
<table class="table table-bordered table-hovered">
<thead>
<tr>
<td class="text-center"><label>ID</label></td>
<td class="text-center"><label>TITLE</label></td>
<td class="text-center"><label>BODY</label></td>
<td class="text-center"><label>CREATED AT</label></td>
<td class="text-center"><label>UPDATED AT</label></td>
</tr>
</thead>
<tbody>
<!-- no output -->
<tr ng-repeat="item in noteListing">
<td>{{ item.id }}</td>
<td>{{ item.title }}</td>
<td>{{ item.body }}</td>
<td>{{ item.created_at }}</td>
<td>{{ item.updated_at }}</td>
</tr>
</tbody>
</table>
</div>
</div>
angular.module('promiseCall',[])
.controller('promiseCtrl', function($scope, $log, noteData) {
$scope.promiseCallRequest = function() {
var getPromiseCallData = noteData.getNoteData();
getPromiseCallData.then({
function(payload) {
console.log(payload); //no output :(
//$scope.noteListing = payload.data;
},
function(errorPayload) {
$log.error('Failure request in note', errorPayload);
}
});
}
}).factory('noteData', function($http, $log, $q) {
return {
getNoteData: function() {
var deferred = $q.defer();
$http.get("<?php echo site_url('tutorial/getAjaxData'); ?>")
.success(function(data){
/*
deferred.resolve({
id: data.id,
title: data.title
});
*/
//console.log('success'); -- ok
})
.error(function(msg, code){
deferred.reject(msg);
$log.error(msg, code);
alert('there must be an error!');
});
return deferred.promise;
}
}
});
Here's the JSON output:
{"article_data":[{"id":"1","title":"sample updated 1","body":"sample 1","created_at":"2015-06-15 15:37
:28","updated_at":"2015-06-15 21:38:46"},{"id":"2","title":"sample 2","body":"sample 2","created_at"
:"2015-06-15 15:37:54","updated_at":"2015-06-15 15:37:54"}]}
Try to remove the {} in your getPromiseCallData.then({});.
E.g.
$scope.promiseCallRequest = function() {
var getPromiseCallData = noteData.getNoteData();
getPromiseCallData.then(
function(payload) {
console.log(payload); //no output :(
//$scope.noteListing = payload.data;
},
function(errorPayload) {
$log.error('Failure request in note', errorPayload);
}
);
};
Hope it helps.
try the below code:
....
getPromiseCallData.then(function(payload) {
console.log(payload); //no output :(
//$scope.noteListing = payload.data;
}).catch(function(errorPayload) {
$log.error('Failure request in note', errorPayload);
});
...
getNoteData: function() {
return $http.get("<?php echo site_url('tutorial/getAjaxData'); ?>");
}
in getNoteData, what you did was a promise anti-pattern, you already have a promise, no need to create another wrapper for it.
Edit:
if you want to log the service's success and error, you could simply do, you still don't need an additional promise:
getNoteData: function() {
return $http.get("<?php echo site_url('tutorial/getAjaxData'); ?>").then(function(data){
//some log
return data;
}, function(err){
// log err
return err;
});
}