displaying params on url disable pagination on ngTable - angularjs

I want to show table parameters (page, count, filter, etc.) in the url. so I use the following code in my controller :
$scope.tableParams = new ngTableParams(
angular.extend({
page : 1,
count: 10
},
$location.search()), {
getData: function ($defer, params) {
$location.search(params.url()); // put params in url
var query = getQuery();
query.limit = params.count();
query.offset = (params.page() - 1) * params.count();
getTotalCount().success(function () {
Content.prototype.find(query)
.success(function (response) {
$scope.tableParams.total($scope.totalCount);
var data = $filter('populateObjects')(response.data, query.fields);
$defer.resolve(data);
});
});
}
});
I do pagination and filtering on server side.
without applying filters on the table everything goes ok and the pagination works correctly. but every time I apply a filter on the table url change twice. the first time it is ok. something like this :
http://faraketabadmin/src/#/content/list?page=7&count=10&filter%5Bname%5D=g&filter%5Btype_id%5D=4
but after a moment it will again reset to page 1 like this :
http://faraketabadmin/src/#/content/list?page=1&count=10&filter%5Bname%5D=g&filter%5Btype_id%5D=4

Related

AngularJS and DataTables refreshing data

My project outputs results to a DataTable from an AngularJS controller function, but I'm running into some strangeness when I try to modify my search params. The first rendering of the table works as expected. But when I select different options and run the search again, extra rows appear in the table, but the info section shows the previous search's row count, and changing the number of rows shown via the length menu causes the new rows to disappear. Here's my table declaration, using attributes to wire up DataTables:
<table ui-jq="dataTable" ui-options="dataTableOptions" id="search-results" class="display nowrap datatable cell-borders" style="width: 100%;">
And this is my AngularJS controller code:
$scope.dataTableOptions = {
dom: "lfBrtip",
lengthMenu: [[25, 50, -1], [25, 50, "All"]],
language: {
emptyTable: 'No items matched your search criteria'
},
buttons: [
{
text: 'Export',
className: 'button button:hover',
extend: 'csv'
}
]
};
$scope.getItemInfo = function (model) {
$http({
method: 'POST',
url: $scope.getUrl('/My/ServerSide/Url'),
data: { model: $scope.model }
}).then(function successCallBack(response) {
$scope.model.SearchResults = response.data;
}, function errorCallback(response) {
alert("There was an error gathering the entity information. Please try again");
});
};
I'm not sure why submitting new queries with different params doesn't simply update the data in the DataTables table. Any suggestions?
I ended up using a bit of an ugly hack to get this to work. Even DataTables author wasn't sure how to get around the issue of using AngularJS with DataTables, so I had to force a reinitialization every time the form posted. I persisted the search params to localStorage, and called location.reload(). Then when the page loads and the AngularJS init() function runs, I pick up the search params and call the search function from inside an Angular document ready function, like this:
$scope.init = function () {
$scope.ValidationErrors = [];
$scope.model = {};
$scope.model.SearchResults = [];
$scope.model.ItemNumber = localStorage.getItem("itemNumber");
$scope.model.StartDate = localStorage.getItem("startDate");
$scope.model.EndDate = localStorage.getItem("endDate");
angular.element(document).ready(function () {
if ($scope.model.ItemNumber) {
$scope.getItemRecords();
}
});
localStorage.clear();
};
And then of course I clear the localStorage after the query. Not terribly elegant, but it'll have to do for now.

pagination with ng-table in angular

I am using ng-table plugin to paginate a table like this:
$scope.ngtableParams = new ngTableParams({}, {
counts:false,
getData: function(params) {
return $http.get($rootScope.app.authApi + 'questions/' + selectedSubtopic.id).then(function(data) {
params.total(data.data.length);
return data.data;
});
}
});
Funnily ng-table calls getData() function everytime a user clicks on page numbers. And hits the entire thing again and fetches all the records and displays them. So pagination is essentially useless.
I need to have a client side pagination. Is it possible with ng-table?
Tried this as well
$http.get($rootScope.app.authApi + 'questions/' + selectedSubtopic.id)
.success(function(data){
$scope.ngtableParams = new ngTableParams({count:5}, {
counts:[],
paginationMaxBlocks: 13,
paginationMinBlocks: 2,
total:data.length,
getData: function(params) {
return data;
}
});
});
Same result with the above as well!
With the latest version of ng-table I end up using the following:
function IssueCtrl(NgTableParams, IssueService) {
var self = this;
loadTable();
function loadTable() {
IssueService.getIssues().then(function (issues) {
self.tableParams = new NgTableParams({
page: 1,
count: 5
}, {
dataset: issues // might be data instead of dataset depending on ng-table version
});
});
}
}
Client side pagination is properly working thanks to dataset.
So it should be something like this for OP:
$http.get($rootScope.app.authApi + 'questions/' + selectedSubtopic.id)
.success(function(result){
$scope.ngtableParams = new ngTableParams({count:5}, {
counts:[],
paginationMaxBlocks: 13,
paginationMinBlocks: 2,
total:result.length,
dataset: result // might be data instead of dataset depending on ng-table version
});
});

Dynamic data is not updated in a ngTable

I'm using the ngTable directive and the problem is that the data doesn't refresh in the table.
When loading the page, the gemId is undefined and no data shows which is ok.
Then you select a value from a dropdown and when pressing a button the loadItems function is called. Data is retrieved from the server but does not show in the table.
When I filter a column, the data is shown (= 2nd request ).
$scope.tblProject = new ngTableParams(tableParameters, {
counts: [], // hide page counts control
total: $scope.items.length, // value less than count hide pagination
//defaultSort: ['asc','desc'];
getData: function ($defer, params) {
//opgelet: request is geldig ondanks de onbestaand igeID;
var gemId = modelFactory.getGemeente().id;
var igeId = 22222;
if(!angular.isUndefined(gemId)){
Project.query({gemId: gemId, igeId: igeId}, function (projecten) {
var orderedData = params.sorting() ? $filter('orderBy')(projecten, params.orderBy()) : projecten;
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
});
}
},
$scope: { $data: {} } //see example 14
});
$scope.$on('loadItems',function() {
$scope.tblProject.reload();
});
Tried all the possible work-arounds for refreshing the table so far, but have had no luck.
edit: I think it is a scope problem when executing the 'loadItems'
The problem was that I was sending an event from the parentController to the childController using $emit instead of $broadcast which executes 'loadItems'

How to reload angular ng-grid onclick?

I'm using angular ng-grid like in this example: http://plnkr.co/edit/50vJrs?p=preview
But I need to load with a new URL the grid when I click for example on the button "reload".
How can I do that?
Define the url in scope variable:
$scope.source="largeLoad.json";
Use this URL in your getPagedDataAsync function instead of an hardcoded source.
$scope.getPagedDataAsync = function (pageSize, page, searchText) {
setTimeout(function () {
var data;
if (searchText) {
var ft = searchText.toLowerCase();
$http.get($scope.source).success(function (largeLoad) {
data = largeLoad.filter(function(item) {
return JSON.stringify(item).toLowerCase().indexOf(ft) != -1;
});
$scope.setPagingData(data,page,pageSize);
});
} else {
$http.get($scope.source).success(function (largeLoad) {
$scope.setPagingData(largeLoad,page,pageSize);
});
}
}, 100);
};
Finaly on reload change the source and call getPagedDataAsync again.
$scope.reload=function(){
$scope.source="largeLoad2.Json";
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, 1);
};
See this Plunker
Modify your getPagedDataAsync function to take a url parameter. Then you can specify which url to load data from.
$scope.getPagedDataAsync = function (url, pageSize, page, searchText) {
Inside the function you can get the data from the url parameter instead of the hardcoded value.
$http.get(url)
Now you can create a reload() function that calls getPagedDataAsync with a new url, and wire it up to a button.
Plunker demo

AngularJS ngTable not updated

I am using Angular routing in my application as well as ngTable. One of my pages contains a ngTable, and a search form, where data is coming from database using GET method (MongoDB) every time I search, so every time I search the ngTable (table) should be updated, and my problem is that the Table is updated only one time, after loading the page for the first time.
The contoller used for the partial page :
app.controller('SearchController',function($scope,ngTableParams,$http,$filter, $sce){
$scope.searching=function(){
var str = $scope.search.tags;
var TagsArry = str.split(",");
$http.get('/api/GetDoc',{params:{title:$scope.search.title,tags:$scope.search.tags}})
.success(function(data)
{
if(data.notExist!=-1){
$scope.tableParams = new ngTableParams({
page: 1, // show first page
count: 10 // count per page
}, {
total: data.length, // length of data
getData: function($defer, params) {
$defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
});
}
})
.error(function(err){
});
}
});
I was having the same issue. You need to reload $scope.tableParams every time a new search occurs, so every time the search button is clicked. A simple way to do this is to wrap $scope.tableParams.reload() in a function, and then call that function when your search button is clicked.
controller code:
$scope.doSearch = function () {
$scope.tableParams.reload();
}
html code:
<button ng-click="doSearch()">Search</button>
I was also having the similar issue. It is a problem with the ngTable directive. It updates only when data.length changes. I had finally solved this issue, simply add this line before your $http request:
$scope['tableParams'] = {reload:function(){},settings:function(){return {}}};
$http.get('/api/GetDoc',{params:{title:$scope.search.title,tags:$scope.search.tags}})
.success(function(data){
/***** Your Code *********/
});
What it does is, it resets the ng-table settings then it initilize like it does for the first time.

Resources