update index.html in angularjs - javascript

Currently our website in angularjs is not updated by latest javascript version without doing hard refresh is browser. In order to update it on real time basis, we have started sending a custom header (APP-VERSION) in our rest API based on which we can reload the page which results in updating the website by latest javascript version.
This version comparision code is written in javascript is the HTTP interceptor which is not updated on client side.
In order to update index.html, we have tried various scenario which are as follows:-
1.We have changed the name of index.html to default.html but still it is not updated on client side.
2.We have changed the path (/test/index.html) of index.html, still its not working.
3.We have used on-page script on every page, we got a warning "Trying to load angularjs twice".
4.We have added the custom header (add_header Cache-Control no-cache;) in the config file on nginx which is also not working/
Please help us how to forcefully update the index.html on client side.
Please find the code index.html, HTTPInterceptor, and route.js
index.html:-
<!DOCTYPE html>
<html>
<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/WebRupee/2.0/font.min.css" />
<link href="https://fonts.googleapis.com/css?family=Noto+Sans" rel="stylesheet">
<!--<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.504/styles/kendo.common.min.css"/>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.504/styles/kendo.rtl.min.css"/>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.504/styles/kendo.silver.min.css"/>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.504/styles/kendo.mobile.all.min.css"/>
-->
<link rel="stylesheet" href="/css/mrConsultant.min.css?ver=##cssVer">
<!-- <link rel="stylesheet" href="css/preLoginPartner.css"> -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<base href="/">
<!-- Google Tag Manager -->
<script>
##gtmScript
</script>
<!-- End Google Tag Manager -->
</head>
<body ng-app="myApp" ng-cloak layout="column">
<div flex layout="column">
<div ng-view flex layout="column"></div>
</div>
<!-- Google Tag Manager (noscript) -->
<noscript>
##gtmNoScript
</noscript>
<!-- End Google Tag Manager (noscript) -->
</body>
<script type="text/javascript" src="js/mrConsultant.min.js?ver=##jsVer"></script>
<!--<script src="http://kendo.cdn.telerik.com/2016.2.504/js/kendo.all.min.js" ></script>
<script src="http://kendo.cdn.telerik.com/2016.2.607/js/kendo.timezones.min.js" ></script>-->
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.6/ngStorage.min.js" async></script>-->
<script src="http://ngmaterial.assets.s3.amazonaws.com/svg-assets-cache.js"></script>
<!--<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular-sanitize.js"></script>-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.6.1/angular-sanitize.min.js"></script>
<noscript>test scritp</noscript>
</html>
HTTPInterceptor:-
myApp.factory('HTTPInterceptor', ['$location','$q','API_URL','version','CookieService','$templateCache','$window',function ($location,$q,API_URL,version,CookieService,$templateCache,$window) {
return {
'request': function (config) {
if ((config.url.indexOf('.html') ==-1) && (config.url.indexOf('.svg')==-1)) {
config.url = API_URL + config.url;
if ((config.url.indexOf('/forgot-password-consultant')==-1) && (config.url.indexOf('/reset-password-consultant')==-1)) {
config.headers['Authorization'] = CookieService.getCookie('AUTH_TOKEN');
}
config.headers['Accept'] = "application/vnd.refer.v1+json";
}
return config;
},
'response': function (resp) {
function createCustomAlert() {
d = document;
if(d.getElementById("website-update")) return;
mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
mObj.id = "website-update";
style = mObj.appendChild(d.createElement("style"));
style.innerHTML = "#import url('https://fonts.googleapis.com/css?family=Roboto')";
alertObj = mObj.appendChild(d.createElement("div"));
alertObj.id = "website-update-card";
h1 = alertObj.appendChild(d.createElement("h1"));
h1.appendChild(d.createTextNode("UPDATE ALERT"));
msg = alertObj.appendChild(d.createElement("p"));
msg.innerHTML = "A new version of Refer is available now. Update now for better performance.";
msg1 = alertObj.appendChild(d.createElement("p"));
msg1.innerHTML = "If you are on an important task, continue your work and you can update on next page.";
updateBtn = alertObj.appendChild(d.createElement("button"))
updateBtn.id = "website-update-btn";
updateBtn.innerHTML = "Update Now";
updateBtn.onclick = function() { clearTemplateCache();return true; }
notUpdateBtn = alertObj.appendChild(d.createElement("button"))
notUpdateBtn.id = "website-update-notnow";
notUpdateBtn.innerHTML = "Not now";
notUpdateBtn.onclick = function() { removeCustomAlert();return false; }
}
function removeCustomAlert() {
document.getElementsByTagName("body")[0].removeChild(document.getElementById("website-update"));
}
function clearTemplateCache() {
document.getElementsByTagName("body")[0].removeChild(document.getElementById("website-update"));
$templateCache.removeAll();
$window.location.reload();
}
if (resp.status === 401) {
$templateCache.removeAll();
$window.location.reload();
$location.path('/logout');
}/*else if(resp.status === 200 && resp.headers('app-version') != null && resp.headers('app1-version') != version){
createCustomAlert();
}*/
return resp;
},
'responseError': function (rejection) {
if(rejection.status === 401) {
$templateCache.removeAll();
$location.path('/logout');
}
return $q.reject(rejection);
}
};
}]);
myApp.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('HTTPInterceptor');
}]);
route.js:-
myApp.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
if(window.history && window.history.pushState){
$locationProvider.html5Mode({
enabled: true,
requireBase: true,
rewriteLinks: true
});
}
$routeProvider.when('/unicorn-:startups-:consultant-:register', {
templateUrl: 'views/registerCampaign.html',
controller: 'RegisterController',
controllerAs: 'registerCtrl'
}).when('/register', {
templateUrl: 'views/register.html',
controller: 'RegisterController',
controllerAs: 'registerCtrl'
}).when('/login', {
templateUrl: 'views/login3.html',
controller: 'LoginController',
controllerAs: 'loginCtrl',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/jobs')
} else {
$location.path('/login');
}
}]
}
}).when('/forgot-password', {
templateUrl: 'views/forgotPassword.html',
controller: '' +
'forgotPasswordController'
}).when('/reset-password/:token/:sm', {
templateUrl: 'views/resetPassword.html',
controller: 'resetPasswordController'
}).when('/logout', {
resolve: {
auth: ['$location', 'UserService', function ($location, UserService) {
UserService.logout();
$location.path('/login');
$location.replace();
}]
}
}).when('/', {
templateUrl: 'views/dashboard.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/dashboard')
} else {
$location.path('/login');
}
}]
}
}).when('/dashboard', {
templateUrl: 'views/dashboard1.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/dashboard')
} else {
$location.path('/login');
}
}]
}
}).when('/jobs/:jobType', {
templateUrl: 'views/jobs.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/jobs.html'
} else {
$location.path('/login');
}
}]
}
}).when('/job-detail/:jobId', {
templateUrl: 'views/job-detail.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/job-detail.html'
} else {
$location.path('/login');
}
}]
}
}).when('/direct-apply/:jobId', {
templateUrl: 'views/apply-new.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/apply-new.html'
} else {
$location.path('/login');
}
}]
}
}).when('/performance', {
templateUrl: 'views/performance.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/performance')
} else {
$location.path('/login');
}
}]
}
}).when('/calendar', {
templateUrl: 'views/calender.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/calendar')
} else {
$location.path('/login');
}
}]
}
}).when('/tracker', {
templateUrl: 'views/tracker.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/tracker')
} else {
$location.path('/login');
}
}]
}
}).when('/internal-jobs', {
templateUrl: 'views/internal-jobs.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/internal-jobs')
} else {
$location.path('/login');
}
}]
}
}).when('/assigned-jobs', {
templateUrl: 'views/assigned-jobs.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/assigned-jobs')
} else {
$location.path('/login');
}
}]
}
}).when('/suggested-candidates/:jobId', {
templateUrl: 'views/suggested-candidates.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/suggested-candidates.html'
} else {
$location.path('/login');
}
}]
}
}).when('/suggested-apply/:jobId', {
templateUrl: 'views/apply-suggested.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/apply-suggested.html'
} else {
$location.path('/login');
}
}]
}
}).when('/edit-candidate/:jobId', {
templateUrl: 'views/edit-candidate.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/edit-candidate.html'
} else {
$location.path('/login');
}
}]
}
}).when('/database', {
templateUrl: 'views/database.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/database.html'
} else {
$location.path('/login');
}
}]
}
}).when('/database-search', {
templateUrl: 'views/database-search.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/database-search.html'
} else {
$location.path('/login');
}
}]
}
}).when('/database-search-result', {
templateUrl: 'views/database-search-result.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/database-search-result.html'
} else {
$location.path('/login');
}
}]
}
}).when('/review-compare', {
templateUrl: 'views/review-compare.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/review-compare.html'
} else {
$location.path('/login');
}
}]
}
}).when('/add-new', {
templateUrl: 'views/add-contact.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/add-contact.html'
} else {
$location.path('/login');
}
}]
}
})
.otherwise({
redirectTo: '/'
});
}]);
myApp.run(['$rootScope', '$templateCache', function ($rootScope, $templateCache) {
$rootScope.$on('$viewContentLoaded', function () {
$templateCache.removeAll();
});
}]);
nginx settings:-
location / {
add_header Cache-Control no-cache;
root D:\refer-workspace\consultant_web;
try_files $uri $uri/ /index.html/ =404;
expires -1;
}
Thanks in advance.

Related

Ionic google maps not loading view with firebase authentication

My ionic 1 project currently has firebase authentication which lets the user log in with an email and password and redirects the user to view that can only be accessed when the user is logged in.
I want to load google maps on the logged in view. I have successfully been able to load google maps on another view that does not firebase authentication in its controller but the minute I put the same code in the controller of the logged in view and setup the div with on the logged in view then it does not load up. There have been no errors in console so im not quite sure what is going on.
So code is as followed:
AuthService calls the firebase service
MuserController (Controller of logged in view):
.controller('MuserCtrl', function($scope, $timeout, $stateParams, ionicMaterialInk, ionicMaterialMotion, $state, AuthService, $cordovaGeolocation) {
$scope.$parent.clearFabs();
$timeout(function() {
$scope.$parent.hideHeader();
}, 0);
ionicMaterialInk.displayEffect();
$scope.current_user = {};
var current_user = AuthService.getUser();
//if user is already logged in
if(current_user) {
//If facebook login
if (current_user && current_user.provider == "facebook") {
$scope.current_user.email = current_user.facebook.displayName;
$scope.current_user.image = current_user.facebook.profileImageURL;
}
//If email login
else {
/*Google Map setting*/
var options = {timeout: 10000, enableHighAccuracy: true};
$cordovaGeolocation.getCurrentPosition(options).then(function(position){
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
}, function(error){
console.log("Could not get location");
});
$scope.current_user.email = current_user.password.email;
$scope.current_user.image = current_user.password.profileImageURL;
}
//No user is currently logged in
} else {
$state.go('app.start');
}
//Logout Function
$scope.logout = function(){
AuthService.doLogout();
$state.go('app.start');
};
})
Services.js (Firebase Authentication Service):
angular.module('socialAuth',[])
.service('AuthService', function($q){
var _firebase = new Firebase("https://logfirebase.firebaseio.com/");
// var _firebase = new Firebase("https://geomuse-169214.firebaseio.com");
// var config = {
// apiKey: "AIzaSyBwdvuilAWOU9DttaGPabpKsHIDHJOuF1Q",
// authDomain: "geomuse-169214.firebaseapp.com",
// databaseURL: "https://geomuse-169214.firebaseio.com",
// projectId: "geomuse-169214",
// storageBucket: "geomuse-169214.appspot.com",
// messagingSenderId: "103764525324"
// };
// firebase.initializeApp(config);
// var rootRef = firebase.database().ref();
this.userIsLoggedIn = function(){
var deferred = $q.defer(),
authService = this,
isLoggedIn = (authService.getUser() !== null);
deferred.resolve(isLoggedIn);
return deferred.promise;
};
this.getUser = function(){
return _firebase.getAuth();
};
this.doLogin = function(user){
var deferred = $q.defer();
_firebase.authWithPassword({
email : user.email,
password : user.password
}, function(errors, data) {
if (errors) {
var errors_list = [],
error = {
code: errors.code,
msg: errors.message
};
errors_list.push(error);
deferred.reject(errors_list);
} else {
deferred.resolve(data);
}
});
return deferred.promise;
};
this.doFacebookLogin = function(){
var deferred = $q.defer();
_firebase.authWithOAuthPopup("facebook", function(errors, data) {
if (errors) {
var errors_list = [],
error = {
code: errors.code,
msg: errors.message
};
errors_list.push(error);
deferred.reject(errors_list);
} else {
deferred.resolve(data);
}
});
return deferred.promise;
};
this.doSignup = function(user){
var deferred = $q.defer(),
authService = this;
_firebase.createUser({
firstname : user.firstname,
lastname : user.lastname,
email : user.email,
password : user.password,
gender : user.gender
}, function(errors, data) {
if (errors) {
var errors_list = [],
error = {
code: errors.code,
msg: errors.message
};
errors_list.push(error);
deferred.reject(errors_list);
} else {
// After signup we should automatically login the user
authService.doLogin(user)
.then(function(data){
// success
deferred.resolve(data);
},function(err){
// error
deferred.reject(err);
});
}
});
return deferred.promise;
};
this.doLogout = function(){
_firebase.unauth();
};
})
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="lib/ion-md-input/css/ion-md-input.min.css" rel="stylesheet">
<link href="lib/ionic-material/dist/ionic.material.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<link href="css/geomuse.css" rel="stylesheet">
<link href="http://code.ionicframework.com/ionicons/1.5.2/css/ionicons.min.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ionic-material/dist/ionic.material.min.js"></script>
<script src="lib/ion-md-input/js/ion-md-input.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
<!--Googple maps plugin-->
<script src="http://maps.google.com/maps/api/js?key=AIzaSyAq9weEMgdVahLcdbvokguOZDuZ3PVVyig&sensor=true"></script>
<!--Firebase-->
<script src="lib/firebase/firebase.js"></script>
<script src="lib/angularfire/dist/angularfire.min.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="starter">
<ion-nav-view></ion-nav-view>
</body>
</html>
muser.html (Logged in view):
<ion-view view-title="Login" align-title="left">
<ion-content>
<div id="map"></div>
</ion-content>
</ion-view>
app.js
angular.module('starter', ['ionic', 'starter.controllers', 'ionic-material', 'ionMdInput', 'ngCordova', 'firebase', 'socialAuth'])
.run(function($ionicPlatform, $state, AuthService, $rootScope) {
$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) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
AuthService.userIsLoggedIn().then(function(response)
{
if(response === true)
{
$state.go('app.muser');
}
else
{
$state.go('auth.connect');
}
});
// 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();
}
});
// UI Router Authentication Check
$rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams){
if (toState.data.authenticate)
{
AuthService.userIsLoggedIn().then(function(response)
{
if(response === false)
{
event.preventDefault();
$state.go('auth.connect');
}
});
}
});
})
.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
// Turn off caching for demo simplicity's sake
$ionicConfigProvider.views.maxCache(0);
/*
// Turn off back button text
$ionicConfigProvider.backButton.previousTitleText(false);
*/
$stateProvider.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
})
.state('app.activity', {
url: '/activity',
views: {
'menuContent': {
templateUrl: 'templates/activity.html',
controller: 'ActivityCtrl'
},
'fabContent': {
template: '<button id="fab-activity" class="button button-fab button-fab-top-right expanded button-energized-900 flap"><i class="icon ion-paper-airplane"></i></button>',
controller: function ($timeout) {
$timeout(function () {
document.getElementById('fab-activity').classList.toggle('on');
}, 200);
}
}
}
})
.state('app.register', {
url: '/register',
views: {
'menuContent': {
templateUrl: 'templates/register.html',
controller: 'ConnectCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
.state('app.register-email', {
url: '/register-email',
views: {
'menuContent': {
templateUrl: 'templates/register-email.html',
controller: 'SignUpCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
.state('app.login', {
url: '/login',
views: {
'menuContent': {
templateUrl: 'templates/login.html',
controller: 'ConnectCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
.state('app.forget-password', {
url: '/forget-password',
views: {
'menuContent': {
templateUrl: 'templates/forget-password.html',
controller: 'ForgetPasswordCtrl'
},
'fabContent': {
template: ''
}
}
})
.state('app.signup', {
url: '/signup',
views: {
'menuContent': {
templateUrl: 'templates/auth/sign-up.html',
controller: 'SignUpCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
.state('app.connect', {
url: '/connect',
views: {
'menuContent': {
templateUrl: 'templates/auth/connect.html',
controller: 'ConnectCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
.state('app.muser', {
url: '/muser',
views: {
'menuContent': {
templateUrl: 'templates/app/muser.html',
controller: 'MuserCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/start');
});
Help would be greatly appreciated

Angular UI router 0.2.15, browser back/forward button not working

I used angular v1.4.7 with UI router 0.2.15, I used $state.go and
ui-sref in case when from html to go to another state. I am unable to
go back. I checked on browser back/forward button but i haven't seen any history got pushed in. So as soon i click on back button it sends me to the empty tab.
'use strict';
/**
* Config for the router
*/
angular.module('app').run(
['$rootScope', '$state', '$stateParams',
function($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
]).config(
['$stateProvider', '$urlRouterProvider', 'JQ_CONFIG', 'MODULE_CONFIG',
function($stateProvider, $urlRouterProvider, JQ_CONFIG, MODULE_CONFIG) {
var layout = "tpl/app.html";
$stateProvider.state('app', {
abstract: true,
url: '/app',
templateUrl: layout,
data: {
permissions: {
exept: ['anonymous'],
redirectTo: 'access.signin'
}
},
resolve: load(['toastr', 'js/controllers/modal.js'])
}).state('app.dashboard', {
url: '/dashboard/:tagName',
templateUrl: 'tpl/app_dashboard_v1.html',
controller: 'DashboardController',
data: {
permissions: {
only: ['USER']
}
},
resolve: load(['toastr', 'js/controllers/dashboard.js'])
}).state('app.chat', {
url: '/chat',
templateUrl: 'tpl/chat.html',
controller: 'chatCtrl',
data: {
permissions: {
only: ['USER']
}
},
resolve: load(['toastr', 'js/controllers/chatCtrl.js'])
}).state('app.accounts', {
url: '/accounts/:accountId/:tagName',
templateUrl: 'tpl/group_dash.html',
controller: 'GroupDashController',
data: {
permissions: {
only: ['USER']
}
},
resolve: load(['toastr', 'js/controllers/group_dashboard.js'])
}).state('app.profile', {
url: '/profile/:accountId',
templateUrl: 'tpl/user_profile.html',
data: {
title: 'Profile'
},
controller: 'UserProfileController',
controllerAs: 'vm',
resolve: load(['toastr', 'js/controllers/profile.js'])
}).state('app.feedback', {
url: '/feedback',
templateUrl: 'tpl/feedback.html',
controller: 'feedbackController',
controllerAs: 'vm',
data: {
permissions: {
only: ['USER']
}
},
resolve: load(['toastr', 'js/controllers/feedback.js'])
}).state('access', {
url: '/access',
template: '<div ui-view class="fade-in-right-big smooth"></div>'
}).state('access.signin', {
url: '/signin',
templateUrl: 'tpl/page_signin.html',
resolve: load(['js/controllers/signin.js'])
}).state('access.signout', {
url: '/signout',
templateUrl: 'tpl/page_signout.html',
controller: "SignoutController",
controllerAs: "vm",
data: {
permissions: {
only: ['USER']
}
},
resolve: load(['js/controllers/signout.js'])
}).state('access.signup', {
url: '/signup',
controller: "SignUpController",
controllerAs: "vm",
templateUrl: 'tpl/page_signup.html',
resolve: load(['toastr', 'js/controllers/signup.js'])
}).state('access.forgotpwd', {
url: '/forgotpwd',
controller: "ForgotPassController",
templateUrl: 'tpl/page_forgotpwd.html',
resolve: load(['js/controllers/forgotpwd.js'])
}).state('access.404', {
url: '/404',
templateUrl: 'tpl/page_404.html'
});
$urlRouterProvider.otherwise(function($injector) {
var $state = $injector.get("$state");
$state.go('app.dashboard');
});
function load(srcs, callback) {
return {
deps: ['$ocLazyLoad', '$q',
function($ocLazyLoad, $q) {
var deferred = $q.defer();
var promise = false;
srcs = angular.isArray(srcs) ? srcs : srcs.split(/\s+/);
if (!promise) {
promise = deferred.promise;
}
angular.forEach(srcs, function(src) {
promise = promise.then(function() {
if (JQ_CONFIG[src]) {
return $ocLazyLoad.load(JQ_CONFIG[src]);
}
angular.forEach(MODULE_CONFIG, function(module) {
if (module.name == src) {
name = module.name;
} else {
name = src;
}
});
return $ocLazyLoad.load(name);
});
});
deferred.resolve();
return callback ? promise.then(function() {
return callback();
}) : promise;
}
]
}
}
}
]);

angularjs after login success redirect home page error

When login success and the page will redirect homepage,I use $state.go('home'),but console error
and actually the browser url was changed http://127.0.0.1:4000/#/home
I don't know how to fixed.
userService.js
angular.module('app')
.factory('userService', ['$http', '$q', function($http, $q) {
function retrieveInstance(type, json) {
var instance = cache[type];
if (instance) {
instance.setProperties(json);
cache[type] = instance;
}
return instance;
}
return {
login: function(username, password) {
var deferred = $q.defer();
var data = {
username: username,
password: password
};
var noramlUrl = '/login/';
$http.post(serverUrl + noramlUrl, data)
.success(function(jsonObj) {
if (jsonObj.isSucc) {
console.log(jsonObj.msg);
deferred.resolve(jsonObj);
} else {
deferred.reject();
}
})
.error(function() {
console.log("login error!");
deferred.reject();
});
return deferred.promise;
},
};
}]);
app.js
angular.module('app', [
'ngMaterial',
'ngMessages',
'material.svgAssetsCache',
'ui.router',
'oc.lazyLoad'
])
.config(['$stateProvider', '$urlRouterProvider',
'$ocLazyLoadProvider',
function($stateProvider, $urlRouterProvider, $ocLazyLoadProvider)
{
$ocLazyLoadProvider.config({
debug: true,
catch: true,
events: true,
// modules: {
// name: '',
// files: []
// }
});
$urlRouterProvider.otherwise('/home');
$stateProvider.state('home', {
url: '/home',
controller: 'homeCtrl',
templateUrl: 'home/template/home.tpl.html',
resolve: {
load: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load([
'home/controller/home.ctrl.js',
'home/css/home.css',
'common/css/common.css'
]);
}]
}
})
.state('login', {
url: '/login',
controller: 'loginCtrl',
templateUrl: 'login/template/login.tpl.html',
resolve: {
load: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load([
'login/controller/login.ctrl.js',
'login/service/userService.js',
'common/css/common.css',
'login/css/login.css'
]);
}]
}
});
}
]);
var serverUrl = 'http://192.168.31.159:8080';
angular.element(document).ready(function() {
angular.bootstrap(document, ['app']);
});
catch: true,
events: true,
// modules: {
// name: '',
// files: []
// }
});
$urlRouterProvider.otherwise('/home');
$stateProvider.state('home', {
url: '/home',
controller: 'homeCtrl',
templateUrl: 'home/template/home.tpl.html',
resolve: {
load: ['$ocLazyLoad',
function($ocLazyLoad) {
return $ocLazyLoad.load([
'home/controller/home.ctrl.js',
'home/css/home.css',
'common/css/common.css'
]);
}]
}
})
.state('login', {
url: '/login',
controller: 'loginCtrl',
templateUrl: 'login/template/login.tpl.html',
resolve: {
load: ['$ocLazyLoad',
function($ocLazyLoad) {
return $ocLazyLoad.load([
'login/controller/login.ctrl.js',
'login/service/userService.js',
'common/css/common.css',
'login/css/login.css'
]);
}]
}
});
}
]);
var serverUrl = 'http://192.168.31.159:8080';
angular.element(document).ready(function() {
angular.bootstrap(document, ['app']);
});
login.ctrl.js
angular.module('app', [])
.controller('loginCtrl', ['$scope', '$state', '$http', '$q',
'userService', function($scope, $state, $http, $q,
userService) {
$scope.name = "login.ctrl Module";
console.log($scope.name);
$scope.login = function() {
userService.login($scope.username,
$scope.password).then(function(json) {
if (json.isSucc) {
console.log(json.isSucc);
$state.go('home');
}
}, function() {
console.log("login error !");
});
};
}]);

How to decorate current state resolve function in UI-Router? Current function isn't invoked

I'm trying to DRY in $stateProvider and prevent adding the same auth function in each resolve. I've created decorator that in each state change would add this function to current state, but auth function isn't invoked, How to fix it or how to workaround discussed issue?
app.config(function ($stateProvider, $urlRouterProvider, $provide) {
$provide.decorator('$state', function($delegate, $rootScope) {
$rootScope.$on('$stateChangeStart', function(event, state, params) {
if ($delegate.current === "login" || $delegate.current === "register") {
return;
}
console.log("decorator", $delegate);
$delegate.current.resolve = {
auth: ['AuthService', '$stateParams', function(AuthService, $stateParams) {
//how to invoke this function?
if (AuthService.isAuthenticated()) {
return AuthService.me(); //promise
} else {
return false;
}
}]
};
});
return $delegate;
});
states definition:
$stateProvider.state('root', {
abstract: true,
url: '/',
views: {
"": {
controller: 'RootCtrl',
templateUrl: 'views/root.html'
},
"header#root": {
templateUrl: 'views/header.html'
}
}
})
.state('root.home', {
url: urlPrefix,
views: {
"content#artworks": {
templateUrl: 'views/home.html',
//resolve: {
// auth: ['AuthService', '$stateParams', function(AuthService, $stateParams) {
// }]
//}
}
}
})
...
If I understand your requirement correctly, we can use native UI-Router built-in decorator:
decorator(name, func)
Allows you to extend (carefully) or override (at your own peril) the stateBuilder object used internally by $stateProvider. This can be used to add custom functionality to ui-router, for example inferring templateUrl based on the state name... (read more in the doc)
There is a working plunker
So, we can have this var auth
var auth = ['AuthService', '$stateParams',
function(AuthService, $stateParams) {
//how to invoke this function on needed states?
if (AuthService.isAuthenticated()) {
return AuthService.me();
} else {
return false;
}
}
];
And here we just use decorator with some "IF" logic
.config(['$stateProvider',
function($stateProvider) {
$stateProvider.decorator('views', function(state, parent) {
var result = {},
views = parent(state);
// some naive example when to not inject resolve
if (state.name === "home") {
return views;
}
// child already has that in parent
if (state.name.indexOf(".") > 0) {
return views;
}
angular.forEach(views, function(config, name) {
// here inject the resolve (if not existing)
config.resolve = config.resolve || {};
// and extend it with the auth stuff above
config.resolve.auth = auth;
result[name] = config;
});
return result;
});
}
])
And later few our states, which will be extended by the above stuff
$stateProvider
.state('home', {
url: "/home",
templateUrl: 'tpl.html',
})
.state('parent', {
url: "/parent",
templateUrl: 'tpl.html',
controller: 'SharedCtrl',
})
.state('parent.child', {
url: "/child",
templateUrl: 'tpl.html',
controller: 'SharedCtrl',
});
Check it in action here
I realized that $delegate.current object contains only raw stateProvider config data. To wrap resolve function I add my function to $delegate.$current on each state change.
$provide.decorator('$state', function($delegate, $rootScope) {
$rootScope.$on('$stateChangeStart', function(event, state, params) {
if ($delegate.current === "err404" || $delegate.current === "login" || $delegate.current === "register") {
return;
}
console.log("decorator", $delegate);
$delegate.$current.resolve["auth"] = ['AuthService', '$stateParams', function(AuthService, $stateParams) {
if (AuthService.isAuthenticated()) {
console.log('AuthService.me()');
return AuthService.me();
} else {
return false;
}
}]
});
return $delegate;
});
Update
I found related discussion on github, you can add universal resolve function into toState param:
app.run(['$rootScope', '$state',
function($rootScope, $state) {
$rootScope.$on('$stateChangeStart', function(event, toState) {
if (toState.name === "login" || toState.name === "register") {
return;
}
toState["resolve"]["auth"] = ['AuthService', '$stateParams', function(AuthService, $stateParams) {
if (AuthService.isAuthenticated()) {
return AuthService.me();
} else {
return false;
}
}];
});
}
]);

Yeoman: AngularJS & facebook SDK, page not loading

So im new with Angular and i downloaded the Yeoman scaffolding for Angular.JS to fiddle with it a bit.
I'm trying to implement Facebook Login with this library: https://github.com/pc035860/angular-easyfb
Nothing is loading and the console doesnt reflect anything. I'm almost sure the problem has something to do with the injecting of the facebook dependency on the controller.
I have this on my main.js file:
angular.module('circeApp', ['ezfb'])
.controller('MainCtrl', function($scope, ezfb, $window, $location) {
updateLoginStatus(updateApiMe);
$scope.login = function(){
ezfb.login(function(response){
if(response.authResponse){
updateLoginStatus(updateApiMe);
}
}, {scope: 'email,user_likes'});
};
$scope.logout = function(){
ezfb.logout(function(){
updateLoginStatus(updateApiMe);
});
};
function updateLoginStatus(more){
ezfb.getLoginStatus(function(response){
$scope.loginStatus = response;
(more || anular.noop)();
});
}
function updateApiMe(){
ezfb.api('/me', function(response){
$scope.apiMe = response;
});
}
});
And this on my app.js file:
'use strict';
angular.module('circeApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'ezfb'
])
.config(function ($routeProvider, $locationProvider, $httpProvider, ezfbProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/main',
controller: 'MainCtrl'
})
.when('/login', {
templateUrl: 'partials/login',
controller: 'LoginCtrl'
})
.when('/signup', {
templateUrl: 'partials/signup',
controller: 'SignupCtrl'
})
.when('/settings', {
templateUrl: 'partials/settings',
controller: 'SettingsCtrl',
authenticate: true
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
// Intercept 401s and redirect you to login
$httpProvider.interceptors.push(['$q', '$location', function($q, $location) {
return {
'responseError': function(response) {
if(response.status === 401) {
$location.path('/login');
return $q.reject(response);
}
else {
return $q.reject(response);
}
}
};
}]);
})
.run(function ($rootScope, $location, Auth) {
// Redirect to login if route requires auth and you're not logged in
$rootScope.$on('$routeChangeStart', function (event, next) {
if (next.authenticate && !Auth.isLoggedIn()) {
$location.path('/login');
}
});
//Configure ezfb provider aqui
ezfbProvider.setInitParams({
appId: 'XXXXXXXXXXXX',
status: true,
cookie: true,
xfbml: true
});
});
Before this, the page rendered but console told me: "Argument 'MainCtrl' is not a function, got undefined". I fixed a missing parenthesis and made sure ezfb was included in angular.module. Now, the only thing i get is a blank page.

Categories

Resources