Angular Blank page - Random issue - javascript

Some of my customers, got blank page when they enter to my site.
My site based on angular application.
I try many things to restore this "blank page" error, for getting the console errors, but with no success.
I try open the site in different browsers.
Open multiple requests same time.
Windows / Mac.
This is my app.js file
var siteApp = angular.module('siteApp', ['ui.router', 'ngSanitize', 'ngAnimate',
'datatables','datatables.buttons','ngCookies']);
siteApp.config(function ($stateProvider, $urlRouterProvider,$httpProvider) {
$urlRouterProvider.otherwise("/index");
$httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content');
$stateProvider
.state('app', {
url: "/?:site_id",
templateUrl: "/controls/angular/templates/partial/app.html",
abstract: true
})
.state('app.popup', {
}).....
});
siteApp.run(['$rootScope','$cookies','$state','$location','$window',
function(
$rootScope,$cookies, $state, $location,$window) {
$rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
var log_route = $cookies.get("hash_route");
if(log_route && log_route.length){
var date = new Date();
date.setTime(date.getTime()+(-2*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
document.cookie = "hash_route" + "=" + undefined + "; " + expires+"; path=/";
$location.url(log_route);
return null;
}
});
$rootScope.$on('$stateChangeSuccess', function () {
try { if (!$window.ga) {
} else {
//$window.ga('send', 'pageview', { page: $location.path() });
}
} catch (x) {}
});
}
]);
I look for ideas for diagnose or restore this issue, or thing for debugging and getting the data error from customers.

Related

Ionic and Firebase auto login

Since firebase did their major update, it has been nearly impossible for me to find answers to basic questions. Even using their docs.
My question is how do I allow my users to sign in once on my app and stay logged in indefinitely or for a set amount of time?
Once I have a user logged in, how can I access their data? Like first and last name? Do I have to create a database and link to the userID somehow?
I am also struggling to understand how "firebase.auth().signInWithEmailAndPassword(email, password)" works since I am not providing it my firebase url. is it pulling it from the config obj on the index page?
Here is my angular code:
appControllers.controller('userCtrl', ['$scope', '$rootScope', '$ionicPlatform', '$cordovaDevice', '$mdToast', '$mdBottomSheet', '$timeout', '$stateParams', '$state', 'LogIn', 'SignUp', '$http', '$firebaseAuth',
function($scope, $rootScope, $ionicPlatform, $cordovaDevice, $mdToast, $mdBottomSheet, $timeout, $stateParams, $state, LogIn, SignUp, $http, $firebaseAuth) {
var devid;
$scope.id = "1";
$scope.errorMsg = "";
// timeout to get device ID
$timeout(function() {
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
$scope.id = $cordovaDevice.getUUID();
return $scope.id;
}
}, 1000);
// watches change in DEVID
$scope.updateID = function() {
devid = $scope.id;
console.log(devid);
return devid;
};
$scope.initialForm = function() {
$scope.moveBox = function() {
// $("#signupbox").fadeOut();
$('#signupbox').animate({
'marginTop': "+=170px" //moves down
});
$timeout(function() {
$state.go('app.signup');
}, 500);
$timeout(function() {
$('#signupbox').animate({
'marginTop': "-=170px" //moves down
});
}, 1000);
} // end animate
// Toast for empty Fields
$scope.showAlert = function(menuName, time) {
//Calling $mdToast.show to show toast.
$mdToast.show({
controller: 'toastController',
templateUrl: 'toast.html',
hideDelay: time,
position: 'top',
locals: {
displayOption: {
title: menuName
}
}
});
} // End showToast.
// check LogIn
var em, pw;
$scope.user = {};
$scope.updateEmail = function() {
em = $scope.user.email;
console.log(em);
return em;
};
$scope.updatePass = function() {
pw = $scope.user.pass;
console.log(pw);
return pw;
};
// Password Validation
$scope.validatePass = function(ppw) {
if (ppw.length < 8) {
$scope.errorMsg = "Password must be at least 8 characters long";
}
};
// start login
$scope.logInNow = function() {
var sdata = {
em: em,
pw: pw
};
if (pw == "" || pw == null) {
$scope.errorSignIn = "Fields cannot be blank";
}
// FIREBASE LOGIN
else {
firebase.auth().signInWithEmailAndPassword(sdata.em, sdata.pw)
.then(function(authData) {
console.log("Logged in as:", authData.uid);
$state.go('app.types');
}).catch(function(error) {
console.error("Authentication failed:", error);
$scope.errorSignIn = "Email or Password is invalid";
});
}
}
};
$scope.initialForm();
}
]);
Staying logged-in forever is default behaviour, but it is all about cookies, so if Ionic clears cookies the user get logout. I'm not into Ionic so I guess you need to figure it out whether it is something with Ionic. Related Ionic blog post. If you want to logout user at some point you can do this by setting a timer and just logout user after X time passed. Note that this is a client-side operation.
In my web app I did something like this:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
$scope.photoURL = user.photoURL;
$scope.name = user.displayName;
$scope.logged_in = true;
} else {
$scope.photoURL = "";
$scope.name = "";
$scope.logged_in = false;
}
});
It works, since every time user enter app the state is changing I always have correct data (Firebase User Interface). I remember there was another way to make it, but I had some issues.
Firebase is first configured and then initialized and every call you do on your app is configured for your project. So yes it is pulling from config.
By the way. Are you using the new docs like https://firebase.google.com/docs/. I am asking because they are actually pretty nice.

Enabling ng-click to open a link in browser window

I have ng-click producing a valid url from my data but struggling to get to open in a browser window, as this will trigger my 3rd party app to open.
I have tried some options and got a few extra button options(2-6) i have found on Stack and Google, can anyone help with getting it to open in a browser?
Here is an image of app showing the console output when I click on the full width button and the code in a Plunker.
http://i.imgur.com/0tfxTuE.jpg
https://plnkr.co/edit/WBYfa3m19MAwobtdbdfU
// 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','ngCordova'])
.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();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('tabs', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})
.state('tabs.home', {
url: '/home',
views: {
'home-tab' : {
templateUrl: 'templates/home.html'
}
}
})
.state('tabs.list', {
url: '/list',
views: {
'list-tab' : {
templateUrl: 'templates/list.html',
controller: 'ListController'
}
}
})
.state('tabs.detail', {
url: '/list/:aId',
views: {
'list-tab' : {
templateUrl: 'templates/detail.html',
controller: 'ListController'
}
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/tab/home');
})
.controller('ListController', ['$scope', '$http', '$state','$cordovaBluetoothSerial', '$location', function($scope, $http, $state, $cordovaBluetoothSerial, $location) {
$http.get('js/aboDATAONLY.json').success(function(data) {
$scope.orders = data;
$scope.whichorder = $state.params.aId;
})
function onPay() {
var itemsArr = [];
var invoice = {};
var myItems = {};
var myItem = {};
myItem['name'] = "Sphero";
myItem['description'] = "A robotic ball that can be controlled via apps";
myItem['quantity'] = "1.0";
myItem['unitPrice'] = "129.00";
myItem['taxRate'] = '0.0';
myItem['taxName'] = 'Tax';
itemsArr.push(myItem);
myItems['item'] = itemsArr;
invoice['itemList'] = myItems;
invoice['paymentTerms'] = 'DueOnReceipt';
invoice['currencyCode'] = 'GBP';
invoice['discountPercent'] = '0';
invoice['merchantEmail'] = 'myemail#mail.com';
invoice['payerEmail'] = 'foo#bar.com';
var returnUrl = 'http://wp1175175.wp220.webpack.hosteurope.de/speedhack/index.html';
var retUrl = encodeURIComponent(returnUrl + "?{result}?Type={Type}&InvoiceId={InvoiceId}&Tip={Tip}&Email={Email}&TxId={TxId}");
var pphereUrl = "paypalhere://takePayment/v2?returnUrl=" + retUrl;
//var pphereUrl = "paypalhere://takePayment/?";
pphereUrl = pphereUrl + "&accepted=cash,card,paypal";
pphereUrl = pphereUrl + "&step=choosePayment";
pphereUrl = pphereUrl + '&invoice=' + escape(JSON.stringify(invoice));
console.log(pphereUrl);
return pphereUrl;
}
$scope.pay = function () {
window.location = onPay();
};
}]);
give a try with
var url = onPay();
window.open(url , '_blank');

Create cookie using ionic angularjs and persist the cookie to a long time

I do create a login system into Ionic/angularjs framework.
I would like to store a cookie and set the expires for a long time, so the user does not need to login every time as it is an internal app.
I just add http post to this controller, could not handle the cookie dependencies yet and the cookie creation:
.controller('AppCtrl', function($scope, $ionicModal, $timeout, $http, $location, $state ) { //, $cookieStore, Auth
$scope.loginData = {};
$scope.doLogin = function() {
if(!angular.isDefined($scope.loginData.login)
|| !angular.isDefined($scope.loginData.password)
|| $scope.loginData.login.trim() == ""
|| $scope.loginData.password.trim() == ""){
alert("Digite seu usuário e senha");
return;
}
$http.post('http://www.somedomain.com/somefile.php',$scope.loginData)
.then(
function(result) {
$scope.response = result;
angular.forEach(result.data, function(value, key) {
console.log(key + ': ' + value);
if( value.slice(-1) == 1 ) {
$location.path('/app/playlists');
} else {
$ionicModal.fromTemplate('<button class=button>try again</button>').show();
}
});
});
};
$scope.logout = function() {
Auth.logout();
$state.go("acesso");
};
})
Use angular-local-storage , you can work with setStorageCookie, here is the link to documentation : https://github.com/grevory/angular-local-storage

Angular JS - dynamic url params and custom url access redirect

I'm just trying to get this to work:
.....
.when('/channel/:id/:slug',{
templateUrl:'views/channel/index.html',
controller:'Channel',
publicAccess:true,
sessionAccess:true
})
.....
app.controller('Channel', ['$scope','$routeParams', function ($scope,$routeParams) {
}]);
app.run(function($rootScope, $location, $route) {
var routesOpenToSession = [];
angular.forEach($route.routes, function(route, path) {
console.log(path);
console.log(route);
route.sessionAccess && (routesOpenToSession.push(path));
});
$rootScope.$on('$routeChangeStart', function(event, nextLoc, currentLoc) {
var closedToSession = (-1 === routesOpenToSession.indexOf($location.path()));
if(closedToSession && $rootScope.session.id_user) {
$location.path('/');
}
});
});
why i can't access the page via site.com/channel/9/my-slug also if $rootScope.session.id_user exists and sessionAccess:true ?
i get redirected to / , while any other static url are ok using sessionAccess:true for example channel/staticparam is ok but with dynamic params it won't work
this is the console log result :
fixed sorry for the stupid question:
/*Not logged redirects*/
app.run(['$rootScope','$location','$route', function ($rootScope, $location,$route) {
var routesOpenToPublic = [];
angular.forEach($route.routes, function (route, path) {
if(route.publicAccess){ routesOpenToPublic.push(route.regexp); }
});
$rootScope.$on('$routeChangeStart', function (event, nextLoc, currentLoc) {
var next_url_regexp = nextLoc.$$route.regexp;
//redirect for not logged users users
if(routesOpenToPublic.indexOf(next_url_regexp) < 0){
$location.path('/auth/login');
}
});
}]);
/*Logged redirects*/
app.run(['$rootScope','$location','$route', function ($rootScope, $location, $route) {
if($rootScope.session && $rootScope.session.id_user){
var routesOpenToSession = [];
angular.forEach($route.routes, function (route, path) {
if(route.sessionAccess){ routesOpenToSession.push( route.regexp);}
});
$rootScope.$on('$routeChangeStart', function (event, nextLoc, currentLoc) {
var next_url_regexp = nextLoc.$$route.regexp;
//redirect for not allowed session users
if(routesOpenToSession.indexOf(next_url_regexp) < 0){
$location.path('/');
}
});
}
}]);
i needed to check the route regexp and not the static url path

Scope are not updated AngularJS

I'm sad... I cook porridge of the ax..
Please, if you can - help me deal with my problem.
I have this structure in my html code(ng-controller is on wrap tag):
<a ng-repeat="subitem in cur_submenu" ng-href="#/{{subitem.href}}/">{{subitem.name}}</a>
In JS I have:
1) RouteProvider
$routeProvider.
when('/:lvl1', {
template:'<div ng-include="htmlUrl">Loading...</div>',
controller: 'MainCtrl'
})
2) Controller
function MainCtrl($scope, $http, $routeParams){
var lvl = window.location.hash.split('/');
if ($scope.submenu) {
//if data was fetch earlier, then set currentMenu
$scope.cur_submenu = $scope.submenu[lvl[1]];
} else {
MainCtrl.prototype.fetchData();
}
MainCtrl.prototype = {
fetchData: function(){
/*
* Get data about navigation
*/
$http({method: 'GET', url: 'data/main.json'}).
success(function(data){
$scope.menu = data.menu;
$scope.submenu = data.submenu;
$scope.cur_submenu = data.submenu[lvl[1]] //current submenu for my location
});
}
}
But it is not updating on my page, when I changed my location on a website(hash-nav)... Please help my. Full version of my site: http://amiu.ru
You don't need to add a function to your Controller with prototyping. Functions called in your view are to be declared on the $scope like so:
function MainCtrl($scope, $http, $routeParams){
var lvl = window.location.hash.split('/');
if ($scope.submenu) {
//if data was fetch earlier, then set currentMenu
$scope.cur_submenu = $scope.submenu[lvl[1]];
} else {
$scope.fetchData();
}
$scope.fetchData = function(){
/*
* Get data about navigation
*/
$http({method: 'GET', url: 'data/main.json'}).
success(function(data){
$scope.menu = data.menu;
$scope.submenu = data.submenu;
$scope.cur_submenu = data.submenu[lvl[1]] //current submenu for my location
});
};
}
In all other cases, if you're executing changes on a $scope outside of a $scope function, you'll need to manually call $scope.$apply() to queue a digest and update your view.

Categories