Angular login auth what about using web worker? - angularjs

What do you think about this approach
using web worker for angular login/auth
it looks good at me and in this way you can get rid of
$rootScope event as well :)
This is just an example in a more prodution way
you should use like https://stackoverflow.com/a/16730809
Html & js
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>Form</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body ng-controller="LoginController as vm">
<p ng-if="vm.isLogged">Logged as {{vm.username}}</p>
<a href ng-click="vm.doFakeLogin()">Login</a>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.2/angular.min.js">
</script>
<script>
function LoginController($scope){
var vm = this;
vm.isLogged = false;
var workerCheckLogin = new Worker('worker-check-login.js');
var workerDoLogin = new Worker('worker-do-login.js');
var jwt = 'auth-token';
workerCheckLogin.postMessage(jwt);
workerCheckLogin.addEventListener('message', function(e) {
if(e.data > 0){
$scope.$evalAsync(function() {
vm.isLogged = true;
vm.username = 'Whisher';
});
}
}, false);
vm.doFakeLogin = function doFakeLogin(){
workerDoLogin.postMessage({username:'whisher','password':'12345'});
}
workerDoLogin.addEventListener('message', function(e) {
if(e.data > 0){
$scope.$evalAsync(function() {
vm.isLogged = true;
vm.username = 'Whisher';
});
}
}, false);
}
angular
.module('app', [])
.controller('LoginController',LoginController);
</script>
</body>
</html>
worker-check-login.js
self.addEventListener('message', function(e) {
console.log('Worker check login said: ', e.data);
/*
do xhr to the server
e.data = jwt
return
1 succees
0 fail
*/
self.postMessage(0); //
}, false);
worker-do-login.js
self.addEventListener('message', function(e) {
console.log('Worker do login said: ', e.data);
/*
do xhr to the server
e.data = credentials
return
1 succees
0 fail
*/
self.postMessage(1); //
}, false);

Related

express-angular-node: Voting Application

the following are my two files for a simple voting app and for some reason the button are not increasing the count only when you refresh the voting.html page does both count increase by one. Your help is appreciated.
<!-- voting.html-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Voting</title>
<script src="angular.min.js"></script>
<script>
var app = angular.module('myFirstApp', []);
app.controller('CounterCtrl', function($scope,$http) {
console.log('CounterCtrl started');
// $scope.countA = 0;
// $scope.countB = 0;
// $scope.Acrease = function() {
// console.log('Acrease() called');
// $scope.countA++;
// };
// $scope.Bcrease = function() {
// console.log('Bcrease() called');
// //if($scope.count>0) $scope.count--;$scope.count++;
// $scope.countB++;
// };
function getItemsA() {
$http.get('/voteA').then(function(res) {
$scope.countA = res.data;
//$scope.countA = res.json(A);
console.log('/voteA: ', $scope.countA);
});
}
getItemsA();
function getItemsB() {
$http.get('/voteB').then(function(res) {
$scope.countB = res.data;
//$scope.countA = res.json(A);
console.log('/voteB: ', $scope.countB);
});
}
getItemsB();
// $scope.addItem = function() {
// console.log('addItem()\t newItem=', $scope.newItem);
// $http.get('/list/add/' + $scope.newItem).then(getItems);
// };
});
</script>
</head>
<body ng-app="myFirstApp">
<div ng-controller="CounterCtrl">
<p>Count of A Vote: <b>{{countA}}</b></p>
<p>Count of B Vote: <b>{{countB}}</b></p>
<input type="button" ng-click="getItemsA()" value="A">
<input type="button" ng-click="getItemsB()" value="B">
</div>
</body>
</html>
/***server.js***/
var express = require('express');
var app = express();
app.listen(3001, function() {
console.log('Listening on 3001');
});
// Mount the public directory at /
app.use('/', express.static('./public'));
/********************************************
* This code is for voting.html
*******************************************/
// initialize the votes variables
var A = 0 ;
var B = 0 ;
// add the voteA
app.get('/voteA', function(req,res) {
//res.json(A);
A++
res.json(A);
});
// add the voteB
app.get('/voteB', function(req,res) {
//res.json(A);
B++
res.json(B);
});
This is angular1 I presume.
I think your problem is that your ng-click is calling a function which is not in scope. I believe you should create scope functions:
$scope.getItemsA = function() {
$http.get('/voteA').then(function(res) {
$scope.countA = res.data;
console.log('response recieved');
});
};
Hope it helps..

AjaxCallBack was not called, windows phone phonegap

I am trying to connect WCF RESTful C# API to phonegap application using angularjs. My html working perfect in Web but no in my windows phone.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="myApp">
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Profile</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
</head>
<body>
<div>
<div data-ng-controller="ProfileCtrl">
First Name: {{FirstName}}
Last Name: {{LastName}}
</div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<!--<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>-->
<script type="text/javascript" src="js/angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);
window.jsoncallback = function (json) {
debugger;
if (!json.Error) {
alert("run callback");
//alert("success");
}
else {
alert(json.Message);
}
}
myApp.controller('ProfileCtrl', ["$scope", "$http", function ($scope, $http) {
function LoadProfile() {
debugger;
var call_url = 'http://localhost:53834/LoginService.svc/UserProfile/1';
//For jsonp calling
//alert("Running Jsonp");
//$http.jsonp(call_url).success(function (data) {
// debugger;
//});
alert("Running Ajax");
$.ajax({
url: call_url,
type: "POST",
dataType: "jsonp", // from the server
crossDomain: true,
contentType: "application/json; charset=utf-8", // to the server
jsonpCallback: 'jsoncallback',
success: function (data) {
alert("success");
$scope.FirstName = data.FirstName;
$scope.LastName = data.LastName;
$scope.$apply();
},
}).done(function (data) {
debugger;
console.log(data);
}).fail(function (xhr, status, error) {
debugger;
alert(xhr.status + " " + status + " " + error);
});
};
LoadProfile();
}]);
</script>
</body>
</html>
Here is my html code,
Service code is
public Stream UserProfile(string profileID)
{
TestDBEntities db = new TestDBEntities();
int _ProfileID = Convert.ToInt32(profileID);
tblProfile objtblProfile = db.tblProfiles.Find(_ProfileID);
string jsCode;
JavaScriptSerializer returnList = new JavaScriptSerializer();
string output = returnList.Serialize(objtblProfile);
if (objtblProfile != null)
jsCode = "jsoncallback" + "(" + output + ");";
else
jsCode = null;
WebOperationContext.Current.OutgoingResponse.ContentType = "application/javascript";
return new MemoryStream(Encoding.UTF8.GetBytes(jsCode));
}
I have done all things but not working in my windows phone it is giving an error
200 parserror: jsoncallback was not called
but it is working perfect in Web normally.
The way I made an AJAX request in my application is as below. Take a look and see if this works out for you:
app.ajaxCall = function() {
var xhr = new XMLHttpRequest();
xhr.open('POST', <URL>, false);
//Content-Type can be based on the content you are sending
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var params = <define param string here>;
xhr.send(params);
var isError = false;
try {
if (xhr.status === 200) {
var jsonResponse = JSON.parse(xhr.responseText);
<logic>
}
};
Hope this helps.

Backbone error when I pass a parameter on URL

This is my code:
<!DOCTYPE html>
<html>
<head>
<title>Bakbone pushStat</title>
<script type="text/javascript" src="vendor/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="vendor/underscore-min.js"></script>
<script type="text/javascript" src="vendor/backbone-min.js"></script>
<script type="text/javascript">
(function($){
var AppRouter = Backbone.Router.extend({
routes: {
"/": "initHome",
"home": "initHome",
"projects/(:id)" : "initProject"
}
});
var app_router = new AppRouter;
app_router.on('route:initHome' , function(){
alert('initHome');
});
app_router.on('route:initProject' , function(id){
alert('Projet');
});
$(document).on("click",".links",function(e) {
var href = $(this).attr("href");
var url = lang + "/" + href;
page = $(this).attr("data-id");
var param = $(this).attr("data-param");
if (typeof(param) == 'undefined') { param = ""; }
if(activepage != href && !main.hasClass("loadingPage")){
loader.show();
firstInit = false;
activepage = href;
res = app_router.navigate(url, true);
getContent(page,param);
}
return false;
});
Backbone.history.start({pushState: true, root: "/backbone_pushStat/"});
})(jQuery);
</script>
</head>
<body>
HOME<br/>
TEST<br/>
<div id="default">default</div>
<div id="entrees">entrees</div>
</body>
</html>
When I click the HOME link, it works very well.
But, I don’t know why, I get this error when I click the TEST link (firefox console).
SyntaxError: syntax error
backbone-min.js (ligne 1)
ReferenceError: jQuery is not defined
})(jQuery);
Anything wrong with my code?
Please help.

Phonegap.js on second html page

I basically have two pages in my phonegap application that I am building with PGB (index.html and main.html), that both use angular.js. Index.html is a login for the app, which redirects to main.html afterwards. All my plugins and phonegap.js are being injected fine into main, but none of the inline JS (alerts on doc ready, device ready, window load) are firing, let alone phonegap.js being loaded as well.
Any advice would be appreciated.
Script Includes:
<script src="phonegap.js"></script>
<script src="cdv-plugin-fb-connect.js"></script>
<script src="facebook-js-sdk.js"></script> <script>alert("inside pg");</script>
<script src="childbrowser.js"></script>
<script src="js/jquery.js"></script>
<script src="js/angular.min.js"></script>
<script>alert("here");</script>
<script src="js/controllers.js"></script>
<script src="js/klass.min.js"></script>
<script src="js/code.photoswipe.jquery-3.0.5.min.js"></script>
<script src="js/maskedInput.js" type="text/javascript"></script>
<script src="js/jquery.joyride.js"></script>
<script src="js/jquery.fancybox.pack.js"></script>
<script src="http://connect.facebook.net/en_US/all.js" type="text/javascript"></script>
Scripts:
alert("p2 adding")
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is loaded and it is now safe to make calls PhoneGap methods
//
function onDeviceReady() {
alert("main.html: device is ready");
}
$(window).load(function(){
alert("window.load happening");
})
</script>
<script>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-42023187-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-42023187-1', 'openvino.com');
ga('send', 'pageview');
</script>
<script type="text/javascript">
var objectToLike = window.location;
var FBactivated = false;
FB.init({
appId : '659381964079214', // App ID
channelURL : '', // Channel File, not required so leave empty
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true,
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
getFriends();
testAPI();
FBactivated = true;
}
});
function getFriends() {
var fbUserIDs = []
FB.api('/me/friends', function(response) {
if(response.data) {
$.each(response.data,function(index,friend) {
var id = friend.id;
fbUserIDs.push(id);
});
var dataString = "fbUserIDs="+fbUserIDs.join();
$.ajax({
type: "POST",
data: dataString,
async: false,
url: "http://m.openvino.com/Scripts/faveMatch.php"
}).done(function(data){
console.log(data);
window.localStorage.setItem("fbFriends", data);
console.log("Saved");
});
} else {
alert("Error!");
}
});
}
function testAPI() {
FB.api('/me', function(response) {
//console.log(response, response.email);
var dataString2 = "id=" + response.id;
dataString2 += "&first_name=" + response.first_name;
dataString2 += "&last_name=" + response.last_name;
dataString2 += "&email=" + response.email;
console.log(dataString2);
$.ajax({
type: "POST",
url: "http://m.openvino.com/Scripts/fbconnect.php",
data: dataString2
}).done(function(data){
var dataJSON = $.parseJSON(data);
if (dataJSON[0].STATUS == "FAILURE") {
//console.log(dataJSON[0].MESSAGE);
return false;
} else if (dataJSON[0].STATUS == "SUCCESS") {
window.localStorage.setItem('email',dataJSON[0].COOKIE.email);
window.localStorage.setItem('password',dataJSON[0].COOKIE.password);
window.localStorage.setItem('name_first',dataJSON[0].COOKIE.name_first);
window.localStorage.setItem('name_last',dataJSON[0].COOKIE.name_last);
window.localStorage.setItem('uID',dataJSON[0].COOKIE.uID);
window.localStorage.setItem('phone',dataJSON[0].COOKIE.phone);
window.localStorage.setItem('firstTime',dataJSON[0].COOKIE.firstTime);
}
});
});
}
function fbLogout() {
if (FBactivated) {
try {
FB.logout(function(response) {
window.location.href = "index.html";
});
} catch (err) {
window.location.href = "index.html";
}
} else {
window.location.href = "index.html";
}
}
$(document).ready(function() {
alert("document.ready loaded");
$("#logmeout").click(function(e){
e.preventDefault();
window.localStorage.clear();
fbLogout();
return false;
});
$('.back_btn').click(function(e) {
$('.profile_menu').hide();
history.back();
});
$(document).click(function(e) {
$('.profile_menu').hide();
})
$('.profile_btn').click(function(e) {
$('.profile_menu').slideToggle();
e.stopPropagation();
e.preventDefault();
return false;
});
$('.profile_menu a').each(function() {
$(this).click(function(e) {
$('.profile_menu').hide();
});
});
});
HTML:
<body ng-app="OpenVino">
<div id="fb-root"></div>
<div class="header-wrap">
<header>
<div ng-show="(page != 'list')" class="back_btn"></div>
<img src="imgs/logo_only.png" alt="OpenVino" />
<div class="profile_btn"></div>
</header>
</div>
<div class="profile_menu">
My Favorites
Contact OpenVino
Images
Logout
</div>
<div class="content {{page}}" ng-view></div>
I fixed it with a simple, but disheartening solution: You have to turn your multipage app into a one page app. Unfortunate how phonegap advertises that you can take your HTML, CSS, and JS and build it natively. All of the .js loaded on the second page wouldnt work until I changed my login to a partial and fooled around with the routing.

"Error: $apply already in progress" when using FireBaseAuthClient with AngularJS

I'm trying to record the logged in user in an AngularJS scope, but getting an error when the page first loads up.
Clicking "Login" seems to work, but then logout bails with the same "$apply already in progress" error.
I'm expecting I've just misunderstood how $apply works, can anybody help?
Update:
It works seamlessly if I wrap just the if (user) part in $apply() as follows.
var auth = new FirebaseAuthClient(ref, function(error, user) {
if (user) {
$scope.$apply(function(){ $scope.user = user; });
console.log(user);
} else if (error) {
// I can't vouch for this, haven't tested it
$scope.$apply(function(){ $scope.user = null; });
console.log(error);
} else {
$scope.user = null;
console.log("logged out");
}
});
Original code:
app.js:
var app = angular.module('app', ['firebase']);
controller.js:
app.controller('Login', ['$scope', 'angularFire',
function($scope, angularFire) {
$scope.loginstatus = 'logged out';
var ref = new Firebase("https://app.firebaseio.com/");
var auth = new FirebaseAuthClient(ref, function(error, user) {
if (user) {
$scope.$apply(function(){ $scope.loginstatus = 'logged in'; });
} else if (error) {
$scope.$apply(function(){ $scope.loginstatus = 'error'; });
alert("Login error: " + error);
} else {
$scope.$apply(function(){ $scope.loginstatus = 'logged out'; });
}
});
$scope.login = function(provider, args) {
auth.login(provider, args);
}
$scope.logout = function() {
auth.logout();
}
}]);
index.html:
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<title>App</title>
<script type="text/javascript" src="https://cdn.firebase.com/v0/firebase.js">
<script type="text/javascript" src='https://cdn.firebase.com/v0/firebase-auth-client.js'></script></script>
<script type="text/javascript" src="lib/angular/angular.js"></script>
<script type="text/javascript" src="lib/angularFire.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/controllers.js"></script>
</head>
<body ng-controller="Login">
<p>Login status: {{loginstatus}}</p>
<div class="container">
<h1>Login</h1>
<p>
<button ng-hide="user" ng-click="login('twitter')" class="btn btn-primary btn-large">Login</button>
<button ng-show="user" ng-click="logout()" class="btn btn-primary btn-large">Logout</button>
</p>
</div>
</body>
</html>
$apply is only needed when you're outside of the context of Angular (like a setTimeout, setInterval, or non-Angular XHR callback).
Since FireBaseAuthClient is a tool written with Angular in mind and injected into your controller, it's likely that the callbacks are already wrapped in $scope.$apply. You can fix your code by removing $scope.$apply, so just:
var ref = new Firebase("https://app.firebaseio.com/");
var auth = new FirebaseAuthClient(ref, function(error, user) {
if (user) {
$scope.loginstatus = 'logged in';
} else if (error) {
$scope.loginstatus = 'error';
alert("Login error: " + error);
} else {
$scope.loginstatus = 'logged out';
}
});

Resources