Ionic Framework no refresh list when navigate - angularjs

I am creating a mobile app in AngularJS. I call a resource that calls an API to give me values. Everything works fine, but with slow connections or 3G $ scope not cool me, and therefore when browsing the list of items is old.
SERVICES.JS
.factory('Exercises', function($resource) {
// localhost: Local
// 79.148.230.240: server
return $resource('http://79.148.230.240:3000/wodapp/users/:idUser/exercises/:idExercise', {
idUser: '55357c898aa778b657adafb4',
idExercise: '#_id'
}, {
update: {
method: 'PUT'
}
});
});
CONTROLLERS
.controller('ExerciseController', function($q, $scope, $state, Exercises) {
// reload exercises every time when we enter in the controller
Exercises.query(function(data) {
$scope.exercises = data;
});
// refresh the list of exercises
$scope.doRefresh = function() {
// reload exercises
Exercises.query().$promise.then(function(data) {
$scope.exercises = data;
}, function(error) {
console.log('error');
});
// control refresh element
$scope.$broadcast('scroll.refreshComplete');
$scope.$apply();
}
// create a new execersie template
$scope.newExercise = function() {
$state.go('newExercise');
};
// delete a exercise
$scope.deleteExercise = function(i) {
// we access to the element using index param
var exerciseDelete = $scope.exercises[i];
// delete exercise calling Rest API and later remove to the scope
exerciseDelete.$delete(function() {
$scope.exercises.splice(i, 1);
});
};
})
APP.js
angular.module('wodapp', ['ionic', 'ngResource', 'wodapp.controllers','wodapp.services'])
// Run
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// ionic is loaded
});
})
// Config
.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$stateProvider
.state('slide', {
url: '/',
templateUrl: 'templates/slides.html',
controller: 'SlideController'
})
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginController'
})
.state('dashboard', {
url: '/dashboard',
templateUrl: 'templates/dashboard.html',
controller: 'DashboardController'
})
.state('exercise', {
url: '/exercise',
templateUrl: 'templates/exercises.html',
controller: 'ExerciseController'
})
.state('newExercise',{
url: '/newExercise',
templateUrl: 'templates/newExercise.html',
controller: 'NewExerciseController'
});
$urlRouterProvider.otherwise('/');
});

If you want to reload a part of your controller logic, every time the view is activated:
.controller('ExerciseController', function(
$q,
$scope,
$state,
Exercises,
$ionicView
) {
// reload exercises every time when we enter in the controller
$ionicView.enter(function(){
// This gets executed regardless of ionicCache
Exercises.query(function(data) {
$scope.exercises = data;
});;
});
});
Else, you can use the reload option on .state()

Related

Separate nav from ng-view

I'm brand new to Angularjs and am trying to set up a new site but I'm confused as to the set up. I have a module and am using $route to successfully navigate but I'm lost as to what to do with my nav. When I load the module I want to read my database for a list of links that the user is allowed to access then spit them out in the nav. I don't want to repeat this in every view because I don't need to. So I'm trying to figure out how to run the ajax call once and then keep changing the view (I'd also like to add a class .selected to whatever view they're on). How would I go about doing that, with a directive?
(function () {
var app = angular.module('manage', ['ngRoute', 'manageControllers']);
/*
I've tried this but obviously $http isn't injected. Can I even do that?
var thisApp = this;
$http.get('/test/angular/php/angular.php', {params: {'function': 'nav'}}).then(function successCallback(response) {
});
*/
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'templates/dash.html',
controller: 'DashCtrl'
}).
when('/inventory/', {
templateUrl: 'templates/inventory.html',
controller: 'InventoryCtrl'
}).
when('/inventory/:mvKey', {
templateUrl: 'templates/inventory.html',
controller: 'InventoryCtrl'
}).
when('/inventory/:mvKey/:tab', {
templateUrl: 'templates/inventory.html',
controller: 'InventoryCtrl'
}).
/* etc...*/
}
]);
})();
EDIT:
My attempt at getting the nav to run once
controllers.js
var manageControllers = angular.module('manageControllers', []);
var thisApp = this;
nav = null;
navSelected = '/';
manageControllers.controller('NavCtrl', ['$scope', '$http', function($scope, $http) {
if (thisApp.nav === null) {
$http.get('php/angular.php', {params: {'function': 'nav'}}).then(function successCallback(response) {
console.log(response.data);
thisApp.nav = response.data;
$scope.nav = thisApp.nav;
$scope.select = thisApp.navSelected;
});
} else {
$scope.nav = thisApp.nav;
$scope.select = thisApp.navSelected;
}
}]);
manageControllers.controller('DashCtrl', ['$scope', function($scope) {
thisApp.navSelected = '/';
}]);
I would swith to UI Router (https://github.com/angular-ui/ui-router) instead of $route. It allows you being much more flexible with your routing.
A Small example:
app.config(['$stateProvider',
function($stateProvider) {
$stateProvider.
state('/', {
url: '/',
views: {
'': {
templateUrl: 'templates/dash.html',
controller: 'DashCtrl'
},
'nav#': {
templateUrl: 'path/to/nav.html',
controller: 'NavCtrl'
},
}
}).
state('/inventory/', {
url: '/',
views: {
'': {
templateUrl: 'templates/dash.html',
controller: 'DashCtrl'
},
'nav#': {
templateUrl: 'path/to/nav.html',
controller: 'NavCtrl'
},
}
}).
// ...
and in your index.html
<div ui-view="nav"></div>
<div ui-view ></div>
Take a closer look at UI Router's doc, there's much more you can do with it!

Ionic Angular Firebase pass value to another tab

I'm new on Ionic, and I have been a couple of days with this problem.
I create an app from chat examples, and I want to connect and read to my firebase database. The first part is woking.- I can retreive and show data from firebase, but my problem is when I click on the "Item list" and want to show detail description, I don not understand how to pass value and get the data again.
Here are my scripst:
app.js ( I'm only showing part of them )
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services','firebase'])
.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);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleLightContent();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
$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.dash', {
url: '/dash',
views: {
'tab-dash': {
templateUrl: 'templates/tab-dash.html',
controller: 'DashCtrl'
}
}
})
.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.account', {
url: '/account',
views: {
'tab-account': {
templateUrl: 'templates/tab-account.html',
controller: 'AccountCtrl'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/tab/dash');
});
Here is my services file --- services.js where I connect to Firebase
angular.module('starter.services', [])
.factory('fireBaseData', function($firebase) {
// Might use a resource here that returns a JSON array
var ref = new Firebase("https://scorching-fire-921.firebaseio.com/")
refCorales = new Firebase("https://scorching-fire- 921.firebaseio.com/corales/");
var fireBaseData = {
all: refCorales,
get: function (chatId) {
return $firebase(ref.child('refCorales').child(chatId)).$asObject();
}
};
return {
ref: function() {
return ref;
},
refCorales: function() {
return refCorales;
}
}
});
And finally here is my controller.js
angular.module('starter.controllers', [])
.controller('DashCtrl', function($scope) {})
.controller('ChatsCtrl', function($scope, $firebase, fireBaseData) {
$scope.corales = $firebase(refCorales);
})
.controller('ChatDetailCtrl', function($scope, $stateParams, fireBaseData) {
$scope.corales = refCorales.get($stateParams.chat$id);
})
.controller('AccountCtrl', function($scope) {
$scope.settings = {
enableFriends: true
};
});
When I click on any item of the list, I'm receiving the following error message: TypeError: refCorales.get is not a function
Any idea how to avoid this erro?
In advance, thank you !
Victor
The problem i see is your services code is very unclear and not returning a way to acces var fireBaseData. Also why are you making two firebase references and not simple using ref.child('corales')?
This would be my solution:
.factory('fireBaseData', function($firebase) {
//Firebase reference
var ref = new Firebase("https://scorching-fire-921.firebaseio.com/")
return {
ref: function(){
return ref;
},
//I don't know if this is actually necessary
refCorales: function(){
return ref.child('corales');
},
get: function(chatId){
$firebase(ref.child('corales').child(chatId)).$asObject();
}
};
})
Update
Also some changes for your controller:
.controller('ChatsCtrl', function($scope, fireBaseData) {
$scope.corales = fireBaseData.refCorales();
})
.controller('ChatDetailCtrl', function($scope, $stateParams, fireBaseData) {
$scope.corales = fireBaseData.get($stateParams.chat$id);
})

Refresh $scope and list of items slow connections

I am creating a mobile app in angularjs . I call a resource that calls an API to give me values. Everything works fine , but with slow connections or 3G $ scope not cool me and therefore when browsing the list of items is old
SERVICES.JS
.factory('Exercises', function($resource) {
// localhost: Local
// 79.148.230.240: server
return $resource('http://79.148.230.240:3000/wodapp/users/:idUser/exercises/:idExercise', {
idUser: '55357c898aa778b657adafb4',
idExercise: '#_id'
}, {
update: {
method: 'PUT'
}
});
});
CONTROLLERS
.controller('ExerciseController', function($q, $scope, $state, Exercises) {
// reload exercises every time when we enter in the controller
Exercises.query(function(data) {
$scope.exercises = data;
});
// refresh the list of exercises
$scope.doRefresh = function() {
// reload exercises
Exercises.query().$promise.then(function(data) {
$scope.exercises = data;
}, function(error) {
console.log('error');
});
// control refresh element
$scope.$broadcast('scroll.refreshComplete');
$scope.$apply();
}
// create a new execersie template
$scope.newExercise = function() {
$state.go('newExercise');
};
// delete a exercise
$scope.deleteExercise = function(i) {
// we access to the element using index param
var exerciseDelete = $scope.exercises[i];
// delete exercise calling Rest API and later remove to the scope
exerciseDelete.$delete(function() {
$scope.exercises.splice(i, 1);
});
};
})
APP.js
angular.module('wodapp', ['ionic', 'ngResource', 'wodapp.controllers','wodapp.services'])
// Run
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// ionic is loaded
});
})
// Config
.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$stateProvider
.state('slide', {
url: '/',
templateUrl: 'templates/slides.html',
controller: 'SlideController'
})
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginController'
})
.state('dashboard', {
url: '/dashboard',
templateUrl: 'templates/dashboard.html',
controller: 'DashboardController'
})
.state('exercise', {
url: '/exercise',
templateUrl: 'templates/exercises.html',
controller: 'ExerciseController'
})
.state('newExercise',{
url: '/newExercise',
templateUrl: 'templates/newExercise.html',
controller: 'NewExerciseController'
});
$urlRouterProvider.otherwise('/');
});

AngularJS - Save data to $scope using routes?

i am just learning basics of angular and today it started to change my app using a factory to get data and implementing route provider ! So far everything works fine! But when I try to add data on another view and head back to my list view scope is reloaded again from factory and no added data shows up.
My approach won't work because each time change my view I will call my controller which reloads data from factory! What can I do to make my Add template will work and changes data everywhere else too.
Maybe somebody can give me a tip how to cope with this problem ?
script.js
var app = angular.module('printTrips', ['ngRoute']);
app.factory('tripFactory', function($http) {
return{
getTrips : function() {
return $http({
url: 'trips.json',
method: 'GET'
})
}
}
});
app.controller('TripController', function($scope, $filter, tripFactory) {
$scope.trips = [];
tripFactory.getTrips().success(function(data){
$scope.trips=data;
var orderBy = $filter('orderBy');
$scope.order = function(predicate, reverse) {
$scope.trips = orderBy($scope.trips, predicate, reverse)};
$scope.addTrip = function(){
$scope.trips.push({'Startdate':$scope.newdate, DAYS: [{"DATE":$scope.newdate,"IATA":$scope.newiata,"DUTY":$scope.newduty}]})
$scope.order('Startdate',false)
$scope.newdate = ''
$scope.newiata = ''
$scope.newduty = ''
}
$scope.deleteTrip = function(index){
$scope.trips.splice(index, 1);
}
});
});
view.js
app.config(function ($routeProvider){
$routeProvider
.when('/',
{
controller: 'TripController',
templateUrl: 'view1.html'
})
.when('/view1',
{
controller: 'TripController',
templateUrl: 'view1.html'
})
.when('/view2',
{
controller: 'TripController',
templateUrl: 'view2.html'
})
.when('/addtrip',
{
controller: 'TripController',
templateUrl: 'add_trip.html'
})
.otherwise({ redirectTo: 'View1.html'});
});
Here is my plunker
Thanks for your help
You should use Service instead of Factory.
Services are loaded each time they are called. Factory are just loaded once.
app.service('tripFactory', function($http) {
return{
getTrips : function() {
return $http({
url: 'trips.json',
method: 'GET'
})
}
}
});

$rootScope.currentUser is null on refresh

I was able to get the firebaseSimpleLogin working and storing the current user in the rootScope. When I goto another page and come back to the feed page everything loads, but when I refresh $rootScope.currentUser is null. Has anyone else had this issue?
I have this piece of code in my app.run function:
$rootScope.$on('$firebaseSimpleLogin:login',function(e, auth){
$rootScope.currentUser = User.find(auth.id);
});
And this is my FeedCtrl that is trying to load in the user's posts
app.controller('FeedCtrl',['$scope', '$rootScope','User','Auth','Post',function($scope, $rootScope,User,Auth,Post){
populateFeed();
console.log($rootScope.currentUser);
$scope.logout = function(){
Auth.logout();
};
$scope.savePost = function(){
Post.create($scope.post).then(function(post){
$scope.post.text = "";
});
};
function populateFeed(){
$scope.posts = {};
angular.forEach($rootScope.currentUser.posts,function(id){
$scope.posts[id] = Post.find(id);
});
}
}]);
My Main app Module
var app = angular.module('myapp',['ui.router','firebase']);
app.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state('/',{
url: '/',
controller: 'MainCtrl',
templateUrl: 'views/index.html'
})
.state('feed',{
url: '/feed',
controller: 'FeedCtrl',
templateUrl: 'views/feed.html',
authenticate: true
})
.state('login',{
url: '/login',
controller: 'LoginCtrl',
templateUrl: 'views/login.html'
})
.state('signup',{
url: '/signup',
controller: 'LoginCtrl',
templateUrl: 'views/signup.html'
})
.state('settings',{
url: '/settings',
controller: 'SettingsCtrl',
templateUrl:"views/settings.html"
})
.state('profile',{
url: '/:slug',
controller: 'ProfileCtrl',
templateUrl: 'views/profile.html'
})
.state('profile-about',{
url: '/:slug/about',
controller: 'ProfileCtrl',
templateUrl: 'views/profile.html'
});
$urlRouterProvider.otherwise('/');
})
.constant('FIREBASE_URL','https://{FIREBASE}.firebaseio.com/')
.run(function($rootScope, $state,FIREBASE_URL, $firebaseSimpleLogin, User, Auth){
$rootScope.$on('$stateChangeStart',function(event, next){
if(next.authenticate && !User.getCurrentUser()){
$state.go('login');
}
});
$rootScope.$on('$firebaseSimpleLogin:login',function(e, auth){
$rootScope.currentUser = User.find(auth.id);
});
$rootScope.$on('$firebaseSimpleLogin:logout',function(){
delete $rootScope.currentUser;
$state.go('login');
});
$rootScope.logout = function(){
Auth.logout();
};
});
If you by 'refresh' mean that you hit F5 in the browser that will wipe your $rootscope from memory and you will get null back as you experience (basically your entire app will be 'restarted').
In order to persist values you either need to store them in a cookie or use localStorage/sessionStorage. For example, instead of using $rootscope.currentUser use $window.sessionStorage.currentUser.
To store it in localStorage:
$window.localStorage.setItem("currentUser", currentUser);
or store in json format:
$window.localStorage.setItem("currentUser", angular.toJson(currentUser));
To get it form there:
var currentUser = $window.localStorage.getItem("currentUser");
or if you saved it using the second way:
var currentUser = JSON.parse($window.localStorage.getItem("currentUser"));

Resources