I am trying to create a pagination using Angularjs in Ionic Framework. Please help me to write code of pagination. I am getting data form this json url.
controller.js
angular.module('starter.controllers', [])
.controller('AppCtrl', function($scope, $ionicModal, $timeout) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//$scope.$on('$ionicView.enter', function(e) {
//});
// Form data for the login modal
$scope.loginData = {};
// Create the login modal that we will use later
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
});
// Triggered in the login modal to close it
$scope.closeLogin = function() {
$scope.modal.hide();
};
// Open the login modal
$scope.login = function() {
$scope.modal.show();
};
// Perform the login action when the user submits the login form
$scope.doLogin = function() {
console.log('Doing login', $scope.loginData);
// Simulate a login delay. Remove this and replace with your login
// code if using a login system
$timeout(function() {
$scope.closeLogin();
}, 1000);
};
})
.controller('PlaylistsCtrl', function($scope, $http, $log) {
$http.get('https://raw.githubusercontent.com/bantic/imdb-data-scraping/master/data/movies.json')
.then(function(response)
{
$scope.data = response.data;
});
})
.controller('PlaylistCtrl', function($scope, $stateParams) {
});
app.js
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
})
.state('app.search', {
url: '/search',
views: {
'menuContent': {
templateUrl: 'templates/search.html'
}
}
})
.state('app.browse', {
url: '/browse',
views: {
'menuContent': {
templateUrl: 'templates/browse.html'
}
}
})
.state('app.playlists', {
url: '/playlists',
views: {
'menuContent': {
templateUrl: 'templates/playlists.html',
controller: 'PlaylistsCtrl'
}
}
})
.state('app.single', {
url: '/playlists/:playlistId',
views: {
'menuContent': {
templateUrl: 'templates/playlist.html',
controller: 'PlaylistCtrl'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/playlists');
});
playlists.html
<ion-view view-title="Playlists">
<ion-content>
<ion-list>
<ion-item ng-repeat="playlist in data | firstPage:currentPage*pageSize | limitTo:pageSize" href="#/app/playlists/{{playlist.id}}">
{{playlist.title}}
</ion-item>
</ion-list>
</ion-content>
</ion-view>
<< 1/2/3/4/5 >>
You need to set pageSize to the total number of movies returned as the response does not contain any meta data about the response:
.controller('PlaylistsCtrl', function($scope, $http, $log) {
$http.get('https://raw.githubusercontent.com/bantic/imdb-data-scraping/master/data/movies.json')
.then(function(response)
{
// populate data with the array of movies
$scope.data = response.data;
// set the page size to the total number of movies
$scope.pageSize = $scope.data.length;
});
});
Related
Hi I'm trying to develop (using ionic, so also angular) a feature in which users can see all events, and see all attending participants. Of all these participants there is information available, so I tried making a master-detail pattern within the master-detail (so basically master-detail-detail).
Problem is, it is returning a 404 while the link is http://localhost:8100/evenement/1/deelnemers/1 and the http function should return a JSON object but I couldn't test it since the page or url wasn't found.
app.js
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
var app = angular.module('newsApp', ['ionic']);
app.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state('list',{
url: '/',
templateUrl: 'list.html',
controller: 'ListCtrl'
})
.state('detail',{
url: '/evenement/:eventId',
templateUrl: 'detail.html',
controller: 'DetailCtrl'
})
.state('deelnemer', {
url: '/evenement/:eventId/deelnemers/:deelnemerId',
templateUrl: 'deelnemer.html',
controller: 'DeelnemerCtrl'
})
;
$urlRouterProvider.otherwise("/");
});
app.factory('Evenementen', function($http){
var cachedData;
function getData(callback){
var url = "http://localhost:8080/evenementen";
$http.get(url).success(function(data){
cachedData = data;
callback(data);
});
}
return {
list: getData,
find: function(pid, callback){
$http.get("http://localhost:8080/evenement/"+pid).success(function(data){
console.log("greater succes");
console.log(data);
callback(data);
});
callback(event);
}
};
});
app.controller('ListCtrl', function($scope, $http, Evenementen){
$scope.news = [];
$scope.getMovieDB = function(){
Evenementen.list(function(evenementen){
$scope.evenementen = evenementen;
});
};
$scope.getMovieDB();
});
app.controller('DetailCtrl', function($scope, $http, $stateParams, Evenementen){
Evenementen.find($stateParams.eventId, function(evenement){
$scope.evenement = evenement;
$scope.deelnemers = evenement.alleDeelnemers;
});
});
app.controller('DeelnemerCtrl', function($scope, $http, $stateParams){
$http.get("http://localhost:8080/evenementen/"+ $stateParams.eventId+"/deelnemers/"+$stateParams.deelnemerId)
.success(function(data){
$scope.deelnemer = data;
});
});
app.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
Urls in Angular and ionic use hash, so your url should be:
http://localhost:8100/#/evenement/1/deelnemers/1
I have an ionic app that I'm trying to build some views for. However, for some reason when I create a unique view-name name, my view doesn't work and it redirects to #/tab/home. The view I'm trying to create is called login, it should be accessed by going to #/tab/login.
Here's my full app.js file.
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ui.rCalendar'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
// setup an abstract state for the tabs directive
.state('tab', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})
// Each tab has its own nav history stack:
.state('tab.home', {
url: '/home',
views: {
'tab-home': {
templateUrl: 'templates/tab-home.html',
controller: 'HomeCtrl'
}
}
})
.state('tab.feed', {
url: '/feed',
views: {
'tab-feed': {
templateUrl: 'templates/tab-feed.html',
controller: 'FeedCtrl'
}
}
})
.state('tab.login', {
url: '/login',
views: {
'tab-login': {
templateUrl: 'templates/tab-login.html',
controller: 'LoginCtrl'
}
}
})
.state('tab.chats', {
url: '/chats',
views: {
'tab-chats': {
templateUrl: 'templates/tab-chats.html',
controller: 'ChatsCtrl'
}
}
})
.state('tab.chat-detail', {
url: '/chats/:chatId',
views: {
'tab-chats': {
templateUrl: 'templates/chat-detail.html',
controller: 'ChatDetailCtrl'
}
}
})
.state('tab.events', {
url: '/events',
views: {
'tab-events': {
templateUrl: 'templates/tab-events.html',
controller: 'EventsCtrl'
}
}
})
.state('tab.cart', {
url: '/cart',
views: {
'tab-cart': {
templateUrl: 'templates/tab-cart.html',
controller: 'CartCtrl'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/tab/login');
});
I've got a file called tab-login.html. When I change the view-name from tab-login to anything else that already exists like tab-feed, when I go to #/tab/login it works fine. So it works when it looks like this:
.state('tab.login', {
url: '/login',
views: {
'tab-feed': {
templateUrl: 'templates/tab-login.html',
controller: 'LoginCtrl'
}
}
})
It works just fine...which makes no sense to me. What am I doing wrong? And why is it redirecting to home when I have it set to default to login?
I have a go back button that when i hit the ng-click='goBack()'. i can see the url in the browser that changes from http://app:8888/#/main/payments to http://app:8888/#/main/products/7 which is the right path that I want to go back to but the problem is that the view doesn't transition there.
I have to hit refresh button in order to go there or do a window.location.reload after the $ionicHistory.goBack();.
I don't want to reload the whole page I want to transition that view to the previous one.
this is my html
<div class="row">
<div class="col col-25">
<button ng-click="goBack()" class="button button-large button-block button-royal">Go Back</button>
</div>
</div>
this is my controller
.controller('paymentsController', function($scope, $localStorage, $log, $state, $window, $ionicHistory){
$scope.goBack = function(){
$ionicHistory.goBack();
}
})
this is my app.js I don't know if this would help.
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ngStorage'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider){
//$ionicConfigProvider.views.transition('none');
$urlRouterProvider.otherwise('/');
$stateProvider
.state('login',{
url: '/',
templateUrl: 'templates/login.html',
controller: 'loginController'
})
.state('main', {
url: '/main',
templateUrl: 'templates/main.html',
controller: 'mainController',
abstract: true
})
.state('main.categories', {
url: '/categories',
views: {
'categories': {
templateUrl: 'templates/categories.html',
controller: 'categoriesController'
}
}
})
.state('main.products', {
url: '/products/:productId',
views: {
'products': {
templateUrl: 'templates/products.html',
controller: 'productsController'
}
}
})
.state('main.payments', {
url: '/payments',
views: {
'payments': {
templateUrl: 'templates/payments.html',
controller: 'paymentsController'
}
}
})
})
Call this from your controller where you want to go back..
var backCount = 1;
$rootScope.$ionicGoBack();
$rootScope.$ionicGoBack = function(backCount) {
$ionicHistory.goBack(backCount);
};
Use $state to redirect to particular view:
$state.transitionTo('main');
here 'main' is your view name that you have defined into your urlrouterprovider.
OR
You can also use $location
$location.path('main');
don't forget to add $state or $location into your controller's parameter.
I am using ionic framework. I am trying to load login page as first page but cant see its just getting an empty page.
My code looks like
app.js:
app.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})
and controller:
.controller('AppCtrl', function ($scope, $state, $ionicModal) {
$ionicModal.fromTemplateUrl('templates/login.html', function(modal) {
$scope.loginModal = modal;
},
{
scope: $scope,
animation: 'slide-in-up',
focusFirstInput: true
}
);
//Be sure to cleanup the modal by removing it from the DOM
$scope.$on('$destroy', function() {
$scope.loginModal.remove();
});
.controller('LoginCtrl', function ($scope, $state, AuthenticationService) {
$scope.message = "";
$scope.user = {
username: null,
password: null
};
$scope.login = function () {
AuthenticationService.login($scope.user);
};
$scope.$on('event:auth-loginRequired', function (e, rejection) {
console.log('handling login required');
$scope.loginModal.show();
});
$scope.$on('event:auth-loginConfirmed', function () {
$scope.username = null;
$scope.password = null;
$scope.loginModal.hide();
});
But still cant see it.
my app looks like
https://github.com/keithdmoore/ionic-http-auth but without the home page.
Thnx!
try to change your app.config section.
app.config(function ($stateProvider) {
$stateProvider.otherwise({ redirectTo: '/login' });
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
}).state('login', {
url: "/login",
templateUrl: "login.html page url",
controller: 'login controller'
}));
don't need to write any code appcontroller'. Whenever you run the application the url path is should be empty. So this line $stateProvider.otherwise({ redirectTo: '/login' }); helps to open the login screen.
I'm trying to create an SPA where you have to be logged in to access almost everything. So naturally, the default screen you see is the login screen. However, after a user has logged in, no matter what the ui-sref is, ui-router redirects to the login page (even when the user is authenticated). Here is my ui-router code:
(function () {
'use strict';
angular
.module('app', ['ui.router', 'satellizer'])
.config(function ($stateProvider, $urlRouterProvider, $authProvider, $httpProvider, $provide) {
$httpProvider.interceptors.push(['$q', '$injector', function($q, $injector){
return {
responseError: function (rejection) {
var $state = $injector.get('$state');
var rejectionReasons = ['token_not_provided', 'token_expired', 'token_absent', 'token_invalid'];
angular.forEach(rejectionReasons, function (value, key) {
if (rejection.data.error === value) {
localStorage.removeItem('user');
$state.go('auth');
}
});
return $q.reject(rejection);
},
response: function(response) {
var authorization = response.headers('authorization');
if(authorization !== null) {
authorization = authorization.substr(7).trim();
//console.log(authorization);
var $auth = $injector.get('$auth');
$auth.setToken(authorization);
}
return response;
}
}
}]);
$authProvider.loginUrl = 'mingdaograder/api/authenticate';
$stateProvider
.state('users', {
url: '/users',
templateUrl: 'views/userView.html',
controller: 'UserController as user'
})
.state('subjects', {
url: '/users/:user_id/subjects',
templateUrl: 'views/subjectsView.html',
controller: 'SubjectsCtrl as subjectsCtrl'
})
.state('subject', {
url: '/users/:user_id/subjects/:subject_id',
templateUrl: 'views/subjectView.html',
controller: 'SubjectCtrl as subjectCtrl'
})
.state('auth', {
url: '/auth',
templateUrl: 'views/authView.html',
controller: 'AuthController as auth'
});
//.state('otherwise', {
// url: '*path',
// templateUrl: 'views/authView.html',
// controller: 'AuthController as auth'
//});
//$urlRouterProvider.otherwise('/auth');
$urlRouterProvider.otherwise(function($injector, $location) {
console.log("Could not find " + $location);
$location.path('/auth');
});
})
.run(function ($rootScope, $state, $log) {
$rootScope.$on('$stateChangeStart', function (event, toState) {
console.log(toState.name);
var user = JSON.parse(localStorage.getItem('user'));
if (user) {
$rootScope.authenticated = true;
$rootScope.currentUser = user;
}
}
);
}
);
})();
Anytime I try to use $state.go(any state name here) or even type the address into the address bar, I am always redirected to the auth state. On the console the message is "Could not find http://localhost/#/" for every single route. I can type in http://localhost/#/users/5/subjects and I get the same message.
Here is one of my controllers doing a redirect:
(function () {
'use strict';
angular
.module('app')
.controller('AuthController', AuthController);
function AuthController($auth, $state, $http, $rootScope, $log) {
var vm = this;
vm.loginError = false;
vm.loginErrorText;
vm.login = function () {
var credentials = {
username: vm.username,
password: vm.password
};
$auth.login(credentials).then(function () {
return $http.get('api/authenticate/user');
}, function (error) {
vm.loginError = true;
vm.loginErrorText = error.data.error;
}).then(function (response) {
var user = JSON.stringify(response.data.user);
localStorage.setItem('user', user);
$rootScope.authenticated = true;
$rootScope.currentUser = response.data.user;
//$log.info('From AuthCtrl: ' + $rootScope.currentUser.id);
$state.go('subjects', {user_id:$rootScope.currentUser.id});
});
}
}
})();
Any ideas what I'm doing wrong? Thanks a lot for your time.
Update: Ok, I haven't found a way to fix it but I think I may have found a possible cause. It seems to only happen for the routes with parameters. For example, if I go to the users state, whose path is /users, there is no redirect. However, if I go to the subjects state, whose path is /users/:user_id/subjects, it does redirect. It's like the Url matching service can't recognize that /users/5/subjects matches /users/:user_id/subjects, so redirects. Any ideas how to work around this?
I found I didn't have a '/' at the beginning of my initial state url. Every time I navigated to the state, the missing '/' seemed to push it into the stateProvider.otherwise.
state1: 'opportunity'
state1Url : '/opportunity/' <== added initial forward slash to make it work.
state2: 'opportunity.create'
state2Url : 'create/'
The first path to be recognised will be the selected as the current location. This means that the order of your route definitions is crucially important. In your case you only have a single catch-all otherwise route definition and since all routes match this then all routes are directed to your login page ignoring any other route definitions you may have, including all your stateProvider state definitions.
One way to fix this is to remove the urlRouterProvider route definition altogether and instead use the *path syntax provided by ui-router to create an alternative otherwise state (which must be defined last for the same reasons given above).
Therefore your code might look something like this:
$stateProvider
.state('auth', {
url: '/auth',
templateUrl: 'views/authView.html',
controller: 'AuthController as auth'
})
.state('users', {
url: '/users',
templateUrl: 'views/userView.html',
controller: 'UserController as user'
})
.state('subjects', {
url: '/users/:user_id/subjects',
templateUrl: 'views/subjectsView.html',
controller: 'SubjectsCtrl as subjectsCtrl'
})
.state('subject', {
url: '/users/:user_id/subjects/:subject_id',
templateUrl: 'views/subjectView.html',
controller: 'SubjectCtrl as subjectCtrl'
})
.state("otherwise", {
url: "*path",
templateUrl: 'views/authView.html',
controller: 'AuthController as auth'
});
From experience, this is either due to the / missing at either the beginning or the end of the url route property definition.
Make sure for parent routes to add the initial forward slash to your routes.
.state('checkers', {
url: '/checkers/',
templateUrl: 'checkers.html',
controller: 'CheckersController',
title: 'Checker',
})
(function () {
'use strict';
angular
.module('app', ['ui.router', 'satellizer'])
.config(function ($stateProvider, $urlRouterProvider, $authProvider, $httpProvider, $provide) {
$httpProvider.interceptors.push(['$q', '$injector', function($q, $injector){
return {
responseError: function (rejection) {
var $state = $injector.get('$state');
var rejectionReasons = ['token_not_provided', 'token_expired', 'token_absent', 'token_invalid'];
angular.forEach(rejectionReasons, function (value, key) {
if (rejection.data.error === value) {
localStorage.removeItem('user');
$state.go('auth');
}
});
return $q.reject(rejection);
},
response: function(response) {
var authorization = response.headers('authorization');
if(authorization !== null) {
authorization = authorization.substr(7).trim();
//console.log(authorization);
var $auth = $injector.get('$auth');
$auth.setToken(authorization);
}
return response;
}
}
}]);
$authProvider.loginUrl = 'mingdaograder/api/authenticate';
$stateProvider
.state('users', {
url: '/users',
templateUrl: 'views/userView.html',
controller: 'UserController as user'
})
.state('subjects', {
url: '/users/:user_id/subjects',
templateUrl: 'views/subjectsView.html',
controller: 'SubjectsCtrl as subjectsCtrl'
})
.state('subject', {
url: '/users/:user_id/subjects/:subject_id',
templateUrl: 'views/subjectView.html',
controller: 'SubjectCtrl as subjectCtrl'
})
.state('auth', {
url: '/auth',
templateUrl: 'views/authView.html',
controller: 'AuthController as auth'
});
//.state('otherwise', {
// url: '*path',
// templateUrl: 'views/authView.html',
// controller: 'AuthController as auth'
//});
//$urlRouterProvider.otherwise('/auth');
$urlRouterProvider.otherwise(function($injector, $location) {
console.log("Could not find " + $location);
$location.path('/auth');
});
})
.run(function ($rootScope, $state, $log) {
$rootScope.$on('$stateChangeStart', function (event, toState) {
console.log(toState.name);
var user = JSON.parse(localStorage.getItem('user'));
if (user) {
$rootScope.authenticated = true;
$rootScope.currentUser = user;
}
}
);
}
);
})();