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"));
Related
Hello I am working with ionic framework and I want to redirect to another page
after successfully login .When I run project using command:
ionic serve then $state.go working properly but when I run project using
ionic serve --lab it is not working
.controller('AppCtrl', function($scope,$http, $ionicModal,$location,$state, $timeout) {
// 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() {
alert($scope.loginData.username);
alert($scope.loginData.password);
$http({
method: 'POST',
url: 'http://localhost/home_owner12/admin/api/login',
data: {username:$scope.loginData.username,password:$scope.loginData.password},
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'}
})
.then(function successCallback(response)
{
if(response.data.length > 0)
{
$state.go('app.search');
console.log('the state is '+$state.current);
}
else
{
alert("Invalid email or pasword");
///$location.path('/search');
}
}, function errorCallback(response)
{
alert("Invalid email pasword");
});
};
})
here is state:
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',
controller: 'AppCtrl'
}
}
});
and module
angular.module('starter', ['ionic', 'starter.controllers', 'ui.router'])
The app.search page's controller goes to AppCtrl in place.
Because AppCtrl runs a second time, it is entering an infinite loop.
Replace the code with that
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',
controller: 'SearchCtrl'
}
}
});
and
.controller('SearchCtrl', function($scope,$http, $ionicModal,$location,$state, $timeout) {
............
.........
.......
})
I am making a project on my own to practice what I've learned about MEAN stack. In the project I want the user to fill in a form and after it is saved in the database the system to take a use to a second form to fill it in etc. I am angularjs for the front end, and within it I am using ui.route. For some reason my program doesn't go to the second program. I already read about other people with the same problem and I can't find what is wrong with my algorithm. Every form works well by itself or when I Make a call from the toolbar.
Frontend.js
angular
.module('authApp',['auth0', 'angular-storage', 'angular-jwt', 'ngMaterial', 'ui.router',
'AdminUser', 'appProfile', 'appToolbar', 'Mod-Company', 'ModShow'])
.config(function($provide, authProvider, $urlRouterProvider, $stateProvider, $httpProvider, jwtInterceptorProvider,$mdThemingProvider){
/* $mdThemingProvider.theme('docs-dark'); */
$mdThemingProvider.theme('default')
.dark();
$mdThemingProvider.alwaysWatchTheme(true);
authProvider.init({
domain: 'workflowjobs.auth0.com',
clientID: 'SjzgRRh3w4ZEFRGLdglpJYvCPCkM189w'
});
jwtInterceptorProvider.tokenGetter = function(store) {
return store.get('id_token');
}
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'components/home/home.html'
})
.state('company', {
url: '/company',
templateUrl: 'components/company/company.html'
})
.state('singlecompany', {
url: '/singlecompany',
templateUrl: 'components/singlecompany/singlecompany.html'
})
.state('show', {
url: '/show',
templateUrl: 'components/show/show-form.html'
})
.state('ticket', {
url: '/ticket',
templateUrl: 'components/ticket/ticket.html'
})
.state('useradmin', {
url: '/useradmin',
templateUrl: 'components/useradmin/useradmin.html'
})
.state('user', {
url: '/user',
templateUrl: 'components/user/user.html'
})
.state('profile', {
url: '/profile',
templateUrl: 'components/profile/profile.html',
controller: 'profileController',
controllerAs: 'user'
});
From the form I use the controller I need, display the form to be filled in by the user and then I call addcompany() after the user click on the button to save the document on the mongodb database.
<section class="table" ng-controller="CompanyCtrl">
<form name="CompanyForm">
...
<input class="form-control" ng-model="company.name" size="40">
...
<p><md-button class="md-raised md-primary md-hue-1" ng-click="addcompany()" aria-label="next">
Now in this code is where I have the problem. the $location.path('/adminuser') doesn't work:
var app = angular.module('Mod-Company', []);
app.controller('CompanyCtrl', ['$scope', '$http',
function($scope,$http){
var refresh = function() {
$http.get('http://localhost:3001/api/company').success(function(response){
$scope.companylist = response;
$scope.company = "";
});
};
refresh();
$scope.addcompany = function(){
$http.post('http://localhost:3001/api/company', $scope.company).success(function(response) {
refresh();
$location.path('/useradmin');
});
$location.path('/useradmin');
};
Instead of using $location.path('/useradmin'); try $state.go('useradmin');.
If it is still not working, it will be easier to help you if you could share your code in a https://jsbin.com or https://plnkr.co
I'm using angular 1.5.0-beta2
i want to be able to read the parameter /cocktail/:cocktail_name
here i define the app and controller:
var app = angular.module('myalcoholist',['ngMaterial','ngRoute']);
app.controller('CocktailController',['$scope','$http', function ($scope,$http) {
$scope.cocktailStepsRows=null;
$http({
method: 'GET',
url: 'http://api.myalcoholist.com:8888/cocktail/steps/' + $scope.cocktail_name
}).then(function successCallback(response) {
$scope.cocktailStepsRows=response.data;
}, function errorCallback(response) {
alert('error');
});
}]);
as you can see i'm trying to append to the api url $scope.cocktail_name
this is how i configure ng-view:
app.config(['$routeProvider','$locationProvider',
function($routeProvider,$locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when('/',{
templateUrl: 'views/index.html',
controller: 'IndexController'
}).
when('/login', {
templateUrl: 'views/login.html',
controller: 'LoginController'
}).
when('/cocktail/:cocktail_name', {
templateUrl: 'views/cocktail.html',
controller: 'CocktailController'
}).
otherwise({
redirectTo: '/'
});
}]);
as you can see i configured the route properly to receive the cocktail_name parameter.
now the problem i'm having is that in the controller, $scope.cocktail_name is undefined.
in the view when i print cocktail name
{{cocktail_name}}
I receive the parameter properly. why not in the controller?
what am I missing?
You did not copy the parameter value to the scope. Fix it using:
$scope.cocktail_name = $routeParams.cocktail_name
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()
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('/');
});