Angular pagination - update data onclick - angularjs

I'm attempting to implement pagination on a angular/bootstrap site. I have the data showing with the correct # of per-page rows, I have the angular paging showing the right number of pages...but heck if I can find anywhere that tells me HOW to use the paging to refresh my data when a page # is clicked...?! {{currentPage}} is updating, but not sure how to have it call getPresentations to update the list.
<div>
{{noOfPages}} {{currentPage}} {{maxSize}}
<pagination num-pages="noOfPages" current-page="currentPage"></pagination>
</div>
<script type="text/javascript">
angular.module('app', ['ui', 'shared', 'ui.bootstrap']).controller('AppCtl', function ($scope, $http, $window) {
var mvc = $window.MVC;
$scope.noOfPages = 0;
$scope.currentPage = 1;
$scope.maxSize = 5;
$scope.getPresentations = function () {
$http.get(mvc.base + "API/Presentations?page=" + $scope.currentPage + "&itemsPerPage=10")
.success(function (result) {
$scope.presentations = result.Items;
$scope.noOfPages = result.TotalPages;
$scope.currentPage = result.Page;
})
.error(function (result, status) {
$scope.newModal.errors = mvc.getApiErrors(status, result);
});
};
$scope.getPresentations();
});
</script>

You've got 2 options:
$watch the current-page property
use the onSelectPage callback
Here is the relevant page with $watch
$scope.$watch('currentPage', function(newPage){
$scope.watchPage = newPage;
//or any other code here
});
And here one using the callback:
$scope.pageChanged = function(page) {
$scope.callbackPage = page;
$scope.watchPage = newPage;
};
used like:
<pagination on-select-page="pageChanged(page)" num-pages="noOfPages" current-page="currentPage"></pagination>
And finally the working plunk showing the 2 approaches:
http://plnkr.co/edit/UgOQo7?p=preview

#pkozlowski.opensource answer is correct, except recent versions of bootstrap have changed on-select-page to ng-change.

Related

Angularjs pagination data doesn't refresh when links clicked

I have a pagination factory, which I didn't write, i'm just using, it gets passed the $scope and a string, the string representing the http action.
It works with GET requests however I am now trying to implement it on a POST request and for some reason it is not working. The pagination bar is loaded, with the right amount of buttons. e.g I have 1 thousand records it loads 100 buttons 10 records per page but when clicking the buttons the data is static, it doesn't update.
Pagination factory:
angular.module('customers')
.factory('PaginationFactory', PaginationFactory);
function PaginationFactory($scope, action) {
$scope.filteredPages = [];
$scope.currentPage = 1;
$scope.numPerPage = 10;
$scope.maxSize = 15;
$scope.makePages = function () {
$scope.search_customers = [];
angular.forEach($scope.get_list, function (item) {
//Push the items into the list...
if (callerAction == 'search_customers') {
$scope.search_customers.push(item);
}
});
};
$scope.$watch('currentPage + numPerPage', function () {
var begin = (($scope.currentPage - 1) * $scope.numPerPage)
end = begin + $scope.numPerPage;
if (callerAction == 'search_customers') {
var pages = $scope.filteredPages = $scope.search_customers.slice(begin, end);
return pages;
});
$scope.makePages();
}
HTML:
<ul uib-pagination
total-items="search_customers.length"
ng-model="currentPage"
max-size="maxSize"
boundary-link-numbers="true"
rotate="false">
</ul>
Post request:
$scope.searchCustomers = function() {
$scope.status = $scope.selected.charAt(0);
$http.post(API_URL+"v1/customers/search", $scope.searchData)
.then(function (response){
var action = 'search_customers';
$scope.get_list = response.data;
console.log($scope)
new PaginationFactory($scope, action);
}, function (response) {
console.log("no data");
});
If anybody could help would be appreciated. Thank you.

Infinite Scrolling reloads page, Ionic

What is happening is that when I reach the bottom of the page, it refreshes and loads the new data, however it doesn't show the data for the previous and current page.
For example it looks like this:
1
2
3
4
* end of page, refreshes page*
5
6
7
8
My function in my controller:
var i = 0;
$scope.result = [];
$scope.noMoreItemsAvailable = false;
$scope.loadMore = function() {
if (i < 4) {
$http.get(url.recommended + i).success(function(response) {
i++;
$scope.result = $scope.result.push(response);
console.log(response);
$timeout(function() {
$scope.result = response
});
$scope.$broadcast('scroll.infiniteScrollComplete');
});
} else {
$scope.noMoreItemsAvailable = true;
}
}
HTML:
<div class="item item-text-wrap" ng-click="post($event,res)" ng-repeat="res in result" ng-controller="recommendedJobsCtrl" ui-sref="tabs.jobDetails">
<ul>
<li id="jobTitle">{{res.title }}</li>
</ul>
</div>
<ion-infinite-scroll ng-if="!noMoreItemsAvailable" on-infinite="loadMore()" distance="1%"></ion-infinite-scroll>
Well, there are 2 main problems:
You're attributing the value of the push for your array. You shouldn't do this, you just have to do this:
$scope.result.push(response);
You should remove this timeout because it's overriding what you already have:
$timeout(function() {
$scope.result = response
});
By the way, I'd recommend you to create a factory to prevent problems with async data.
You could do something like this:
angular
.module('app', [])
.controller("MainCtrl", MainCtrl)
.factory("ItemsFactory", ItemsFactory);
ItemsFactory.$inject = ['$http'];
function ItemsFactory($http) {
var factory = {
getPages: getPages
};
return factory;
function getPages(url) {
return $http.get(url);
}
}
Then, in your controller:
MainCtrl.$inject = ['$scope', 'ItemsFactory'];
function MainCtrl($scope, ItemsFactory) {
var url = 'https://www.google.com';
function getResponse(response) {
$scope.result.push(response.data);
}
function getError(response) {
console.log(response);
}
ItemsFactory.getPages(url)
.then(getResponse);
.catch(getError);
}
Please, note: I also recommend you to change the way that you're retrieving your items from your back-end. It isn't a good way to retrieve the elements 1 by 1. The correct in your case is to retrieve all the four items at once and treat them in controller.
Your timeout is causing the $scope.result to be overwritten by the response.
Just remove this and it should append the response to the result
REMOVE THIS
$timeout(function ()
{
$scope.result=response
});

Angular binding not working properly with ngInfiniteScroll

Basically I have a timeline with posts that is a $firebaseArray and any change to this array is getting binded properly. But when I want to bind any other data it only binds when ngInfiniteScroll is trying to retrieve more data from firebase, so only when I scroll down.
In the code bellow I'm calling {{getMoreDetails()}} and this data is binded when the first set of data is being retrieved with ngInfiniteScroll but as soon as it is loaded the bind breaks and only binds again when scrolling.
My concerns here are:
Was ngInfiniteScroll designed to work this way?
Is there any workaround in this scenario?
Stack:
"firebase": "2.4.2","angularfire": "~1.2.0","firebase-util": "0.2.5","ngInfiniteScroll": "1.2.2"
timeline.html
<div ng-controller="TimelineController">
<section class="entrys main-content" infinite-scroll="posts.scroll.next(3)" infinite-scroll-distance="0.3">
<div class="inner">
<div ng-repeat="post in filteredPostsResults = (posts | filter:postIdFilter)">
<article class="entry">
<img ng-if="post.sourceType=='IMAGE'" data-ng-src="{{getPostData(post)}}"/>
<div class="entry-info">
<h3><div ng-bind-html="post.description | emoticons"></div></h3>
<small>posted on <time>{{getDateInFormat(post.createdAt)}}</time></small>
{{getMoreDetails()}}
</div>
</article>
</div>
</div>
</section>
</div>
timeline.js
(function (angular) {
"use strict";
var timeline = angular.module('myApp.user.timeline', ['firebase', 'firebase.utils', 'firebase.auth', 'ngRoute', 'myApp.user.timelineService']);
timeline.controller('TimelineController', [ '$scope', '$routeParams', 'TimelineService', '$publisherServices', '$securityProperties', function ($scope, $routeParams, TimelineService, $publisherServices, $securityProperties) {
if (!$scope.posts){
$scope.posts = TimelineService.getPosts($routeParams.userId);
}
$scope.posts.$loaded(function(result) {
$scope.isPostsLoaded = true;
});
$scope.getMoreDetails = function() {
console.log("LOGGED ONLY WHEN SCROLLING");
return $publisherServices.getDetails();
};
$scope.getPostData = function(post) {
if (!post.dataUrl){
post.dataUrl = $publisherServices.getAwsFileUrl(post.fileName);
}
return post.dataUrl;
};
$scope.postIdFilter = function(post) {
if ($routeParams.postId){
if (post.$id == $routeParams.postId) return post;
} else { return post; }
};
$scope.getDateInFormat = function(timestamp){
var date = new Date();
date.setTime(timestamp);
return date;
};
}]);
})(angular);
timelineService.js
(function (angular) {
"use strict";
var timelineService = angular.module('myApp.user.timelineService', []);
timelineService.service('TimelineService', ['$routeParams', 'FBURL', '$firebaseArray', function ($routeParams, FBURL, $firebaseArray) {
var posts;
var currentUserIdPosts;
var postsRef;
var self = {
getPosts: function(userId){
if (!posts || userId != currentUserIdPosts){
currentUserIdPosts = userId;
postsRef = new Firebase(FBURL).child("posts").child(userId);
var scrollRef = new Firebase.util.Scroll(postsRef, "createdAtDesc");
posts = $firebaseArray(scrollRef);
posts.scroll = scrollRef.scroll;
}
return posts;
}
}
return self;
}]);
})(angular);
I am assuming that you want the post details updated when the data from your Firebase changes.
When Firebase changes are applied to your scope, it seems that it doesn't trigger a digest cycle, so you probably need to do it manually every time you get updates from Firebase.
Take a look at $$updated in $firebaseArray.$extend (see docs).
// now let's create a synchronized array factory that uses our Widget
app.factory("WidgetFactory", function($firebaseArray, Widget) {
return $firebaseArray.$extend({
// override the update behavior to call Widget.update()
$$updated: function(snap) {
// we need to return true/false here or $watch listeners will not get triggered
// luckily, our Widget.prototype.update() method already returns a boolean if
// anything has changed
return this.$getRecord(snap.key()).update(snap);
}
});
});
I hope this helps.

Map AngularJS restAPI request via URL

Being new to angular I'm stocked to figure out how to call a web service which should be parsed and maped via URL, like if the URL is getting called directly to get listed request with the given params
what I mean let say I have
/api/products -- calling all products(this is the access point)
/api/products/?page=2&orderby=asc -- calls products with pagination and orderby and here is what's bothering me because the api is getting called via ajax and there is no URL mapping of the target
My Codes
Html markup
<div ng-controller="MainCtrl">
<div class="row">
<div class="col-lg-7 col-md-7 col-sm-7">
<pagination total-items="totalItems" num-pages="totalPages" ng-model="currentPage" ng-change="selectPage(currentPage)" max-size="5" class="pagination-sm" boundary-links="true"></pagination>
</div>
<div ng-repeat="product in products"></div>
</div>
</div>
contoller
//called when navigate to another page in the pagination
$scope.selectPage = function(page) {
$scope.filterCriteria.pageNumber = page;
$scope.fetchResult();
};
//The function that is responsible of fetching the result from the server and setting the grid to the new result
$scope.fetchResult = function() {
return api.items.search($scope.filterCriteria).then(function(data) {
$scope.products = data;
$scope.totalPages = data.total;
$scope.productsCount = data.TotalItems;
}, function() {
$scope.products = [];
$scope.totalPages = 0;
$scope.productsCount = 0;
});
};
Service
.factory('api', function(Restangular) {
//api call to
return {
products: function() {
return Restangular.all('products').getList();
},
product: function(id) {
Restangular.one("products", id ).get().then(function(c) {
return c;
});
},
update: function(id) {
Restangular.one("products", id).put().then(function(c) {
return c;
});
},
items: {
search: function(query) {
return Restangular.all('products').getList(query);
}
},
};
});
How do I create params URL and function of this make restAPI calls or what are the workarounds in this case
You can get at the search parameters with the $location service. So if a user goes to somedomain.com/products/?page=2&orderby=asc then $location.search() will equal {page: 2, orderby: 'asc'}.
So when your controller loads you just need to set the filterCriteria and fetch the results.
controller
var myCtrl = function($location, $scope) {
$scope.selectPage = function(page) {
...
};
$scope.fetchResult = function() {
...
};
$scope.filterCriteria = $location.search();
$scope.fetchResults();
}
First you need to create a restangular object by mentioning the base url. In your case it will be
// It will creat a url /api
var base = Restangular.all('api');
Now you can create multiple scenarios like if you want to get all products then it will be:
// /api/products/
base.getList('products')
.then(function(products) {
$scope.products= products
})
Now if you want to apply pagination as well as include orderBy param
$scope.products = base.getList("products", [{page: 2},{orderby:asc}]);

Angular call service on asynchronous data

I have a service that make some calls to retrieve data to use in my app. After I've loaded data, I need to call another service to make some operations on my data. The problem is that second service will not have access to the data of the first service.
I've made a plunker: plunkr
First service
app.factory('Report', ['$http', function($http,$q){
var Authors = {
reports : [],
requests :[{'url':'data.json','response':'first'},
{'url':'data2.json','response':'second'},
{'url':'data3.json','response':'third'}]
};
Authors.getReport = function(target, source, response, callback) {
return $http({ url:source,
method:"GET",
//params:{url : target}
}).success(function(result) {
angular.extend(Authors.reports, result)
callback(result)
}
).error(function(error){
})
}
Authors.startQueue = function (target,callback) {
var promises = [];
this.requests.forEach(function (obj, i) {
console.log(obj.url)
promises.push(Authors.getReport(target, obj.url, obj.response, function(response,reports){
callback(obj.response,Authors.reports)
}));
});
}
return Authors;
}])
Second service
app.service('keyService', function(){
this.analyze = function(value) {
console.log(value)
return value.length
}
});
Conroller
In the controller I try something like:
$scope.result = Report.startQueue('http://www.prestitiinpdap.it', function (response,reports,keyService) {
$scope.progressBar +=33;
$scope.progress = response;
$scope.report = reports;
});
$scope.test = function(value){
keyService.analyze($scope.report.about);
}
I think this is what you are going for? Essentially, you want to call the second service after the first succeeds. There are other ways of doing this, but based on your example this is the simplest.
http://plnkr.co/edit/J2fGXR?p=preview
$scope.result = Report.startQueue('http://www.prestitiinpdap.it', function (response,reports) {
$scope.progressBar +=33;
$scope.progress = response;
$scope.report = reports;
$scope.test($scope.report.about); //added this line
});
$scope.test = function(value){
$scope.example = keyService.analyze(value); //changed this line to assign property "example"
}
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<p>Progress notification : {{progress}}!</p>
<div ng-show="show">
<progress percent="progressBar" class="progress-striped active"></progress>
</div>
<pre>{{report}}</pre>
<pre>{{report.about}}</pre>
{{example}} <!-- changed this binding -->
</body>

Resources