I am trying to overwrite portions of my single page app using only javascript and AngularJS.
Overwrites are based on subdomain.
Every subdomain is pointing to the same doc root.
controllers.js
controller('AppController', ['$scope','$route','$routeParams','$location', function($scope, $route, $routeParams, $location) {
$scope.$on("$routeChangeSuccess",function( $currentRoute, $previousRoute ){
render();
});
var render = function(){
//Is it actually a subdomain?
if($location.host().split(".",1).length>2){
//Use subdomain folder if it is.
var url = "views/"+$location.host().split(".",1)+"/"+$route.current.template;
var http = new XMLHttpRequest();
http.onreadystatechange=function(){
if (http.readyState==4){
//If there isn't an overwrite, use the original.
$scope.page = (http.status!=404)?url:("views/"+$route.current.template);
}
}
http.open('HEAD', url, true);
http.send();
}
else{
//Else we are on the parent domain.
$scope.page = "views/"+$route.current.template;
}
};
}])
config.js
config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/', {
template: 'home.html'
});
$routeProvider.when('/services', {
template: 'services.html'
});
$routeProvider.otherwise({redirectTo: '/'});
}]);
index.html
<html lang="en" ng-app="myApp" ng-controller="AppController">
<body>
<div ng-include src="page" class="container"></div>
</body>
</html>
Because this is a single page app, when you hit a URL directly, it's going to 404. That's why we apply rewrite rules on the server. In my case I'm using nginx:
location / {
try_files $uri /index.html;
}
This works great when I'm not on a subdomain, but then again I'm also not sending out an XMLHttpRequest. When I do use the subdomain, now we need to check for an overwrite.
The tricky part here is that the rewrite rules are forcing the XMLHttpRequest to return a 200.
Ideas on how I can have my cake and eat it too?
I decided to go with a local stradegy for two reasons:
There is no additional overhead of XML request.
404 messages wont polute console logs when resource doesn't exist.
services.js
factory('Views', function($location,$route,$routeParams,objExistsFilter) {
var viewsService = {};
var views = {
subdomain1:{
'home.html':'/views/subdomain1/home.html'
},
subdomain2:{
},
'home.html':'/views/home.html',
};
viewsService.returnView = function() {
var y = $route.current.template;
var x = $location.host().split(".");
return (x.length>2)?(objExistsFilter(views[x[0]][y]))?views[x[0]][y]:views[y]:views[y];
};
viewsService.returnViews = function() {
return views;
};
return viewsService;
}).
controllers.js
controller('AppController', ['$scope','Views', function($scope, Views) {
$scope.$on("$routeChangeSuccess",function( $currentRoute, $previousRoute ){
$scope.page = Views.returnView();
});
}]).
filters.js
filter('objExists', function () {
return function (property) {
try {
return property;
} catch (err) {
return null
}
};
});
Related
Hi I want to call a function after clicking on a button which is added to dom after angular is loaded. I dont know if this is possible in the way I am trying it, but I do know that my current code doesn't call the alert function.
After sending a search request to my backend, I get a list data entrys, which I display as hrefs.
my_form.setAttribute("href", result[i].url)
my_form.setAttribute("ng-href",'#here')
my_form.setAttribute("ng-click", "alert(1)")
my_form.setAttribute("style", "display:block;")
results in
John Doe
Complete Code:
var appModule = angular.module('graph', [])
appModule.controller('graphCtrl', ['$scope', '$http', '$compile', function ($scope, $http, $compile) {
$scope.search = function () {
var data = {
}
$http.get('/api/search/?q=' + $scope.searchfield, data).success(function (data, status, headers, config) {
var result = data;
var searchResultsContainer = document.getElementById("dropdownId");
while (searchResultsContainer.firstChild) {
searchResultsContainer.removeChild(searchResultsContainer.firstChild);
}
for (i in result) {
var my_form = document.createElement("a");
my_form.setAttribute("href", result[i].url)
my_form.setAttribute("ng-href",'#here')
my_form.setAttribute("ng-click", "alert(1)")
my_form.setAttribute("style", "display:block;")
my_text = document.createTextNode(result[i].caption)
my_form.appendChild(my_text)
searchResultsContainer.appendChild(my_form)
}
})
}
$scope.alert = function(){
alert("Hello! I am an alert box!!");
}
}
I am following this article on Social Logins with AngularJS and ASP.Net WebAPI (which is quite good):
ASP.NET Web API 2 external logins with Facebook and Google in AngularJS app
Pretty much, the code works fine when you are running the social login through a desktop browser (i.e. Chrome, FF, IE, Edge). The social login opens in a new window (not tab) and you are able to use either your Google or Facebook account and once your are logged in through any of them, you are redirected to the callback page (authComplete.html), and the callback page has a JS file defined (authComplete.js) that would close the window and execute a command on the parent window.
the angularJS controller which calls the external login url and opens a popup window (not tab) on desktop browsers:
loginController.js
'use strict';
app.controller('loginController', ['$scope', '$location', 'authService', 'ngAuthSettings', function ($scope, $location, authService, ngAuthSettings) {
$scope.loginData = {
userName: "",
password: "",
useRefreshTokens: false
};
$scope.message = "";
$scope.login = function () {
authService.login($scope.loginData).then(function (response) {
$location.path('/orders');
},
function (err) {
$scope.message = err.error_description;
});
};
$scope.authExternalProvider = function (provider) {
var redirectUri = location.protocol + '//' + location.host + '/authcomplete.html';
var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + "api/Account/ExternalLogin?provider=" + provider
+ "&response_type=token&client_id=" + ngAuthSettings.clientId
+ "&redirect_uri=" + redirectUri;
window.$windowScope = $scope;
var oauthWindow = window.open(externalProviderUrl, "Authenticate Account", "location=0,status=0,width=600,height=750");
};
$scope.authCompletedCB = function (fragment) {
$scope.$apply(function () {
if (fragment.haslocalaccount == 'False') {
authService.logOut();
authService.externalAuthData = {
provider: fragment.provider,
userName: fragment.external_user_name,
externalAccessToken: fragment.external_access_token
};
$location.path('/associate');
}
else {
//Obtain access token and redirect to orders
var externalData = { provider: fragment.provider, externalAccessToken: fragment.external_access_token };
authService.obtainAccessToken(externalData).then(function (response) {
$location.path('/orders');
},
function (err) {
$scope.message = err.error_description;
});
}
});
}
}]);
authComplete.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script src="scripts/authComplete.js"></script>
</body>
</html>
authComplete.js
window.common = (function () {
var common = {};
common.getFragment = function getFragment() {
if (window.location.hash.indexOf("#") === 0) {
return parseQueryString(window.location.hash.substr(1));
} else {
return {};
}
};
function parseQueryString(queryString) {
var data = {},
pairs, pair, separatorIndex, escapedKey, escapedValue, key, value;
if (queryString === null) {
return data;
}
pairs = queryString.split("&");
for (var i = 0; i < pairs.length; i++) {
pair = pairs[i];
separatorIndex = pair.indexOf("=");
if (separatorIndex === -1) {
escapedKey = pair;
escapedValue = null;
} else {
escapedKey = pair.substr(0, separatorIndex);
escapedValue = pair.substr(separatorIndex + 1);
}
key = decodeURIComponent(escapedKey);
value = decodeURIComponent(escapedValue);
data[key] = value;
}
return data;
}
return common;
})();
var fragment = common.getFragment();
window.location.hash = fragment.state || '';
window.opener.$windowScope.authCompletedCB(fragment);
window.close();
The issue I am having is that when I run the application on a mobile device (Safari, Chrome for Mobile), the social login window opens in a new tab and the JS function which was intended to pass back the fragment to the main application window does not execute nad the new tab does not close.
You can actually try this behavior on both a desktop and mobile browser through the application:
http://ngauthenticationapi.azurewebsites.net/
What I have tried so far in this context is in the login controller, I modified the function so that the external login url opens in the same window:
$scope.authExternalProvider = function (provider) {
var redirectUri = location.protocol + '//' + location.host + '/authcomplete.html';
var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + "api/Account/ExternalLogin?provider=" + provider
+ "&response_type=token&client_id=" + ngAuthSettings.clientId
+ "&redirect_uri=" + redirectUri;
window.location = externalProviderUrl;
};
And modified the authComplete.js common.getFragment function to return to the login page, by appending the access token provided by the social login as query string:
common.getFragment = function getFragment() {
if (window.location.hash.indexOf("#") === 0) {
var hash = window.location.hash.substr(1);
var redirectUrl = location.protocol + '//' + location.host + '/#/login?ext=' + hash;
window.location = redirectUrl;
} else {
return {};
}
};
And in the login controller, I added a function to parse the querystring and try to call the $scope.authCompletedCB(fragment) function like:
var vm = this;
var fragment = null;
vm.testFn = function (fragment) {
$scope.$apply(function () {
if (fragment.haslocalaccount == 'False') {
authenticationService.logOut();
authenticationService.externalAuthData = {
provider: fragment.provider,
userName: fragment.external_user_name,
externalAccessToken: fragment.external_access_token
};
$location.path('/associate');
}
else {
//Obtain access token and redirect to orders
var externalData = { provider: fragment.provider, externalAccessToken: fragment.external_access_token };
authenticationService.obtainAccessToken(externalData).then(function (response) {
$location.path('/home');
},
function (err) {
$scope.message = err.error_description;
});
}
});
}
init();
function parseQueryString(queryString) {
var data = {},
pairs, pair, separatorIndex, escapedKey, escapedValue, key, value;
if (queryString === null) {
return data;
}
pairs = queryString.split("&");
for (var i = 0; i < pairs.length; i++) {
pair = pairs[i];
separatorIndex = pair.indexOf("=");
if (separatorIndex === -1) {
escapedKey = pair;
escapedValue = null;
} else {
escapedKey = pair.substr(0, separatorIndex);
escapedValue = pair.substr(separatorIndex + 1);
}
key = decodeURIComponent(escapedKey);
value = decodeURIComponent(escapedValue);
data[key] = value;
}
return data;
}
function init() {
var idx = window.location.hash.indexOf("ext=");
if (window.location.hash.indexOf("#") === 0) {
fragment = parseQueryString(window.location.hash.substr(idx));
vm.testFn(fragment);
}
}
But obviously this is giving me an error related to angular (which I have no clue at the moment):
https://docs.angularjs.org/error/$rootScope/inprog?p0=$digest
So, pretty much it is a dead end for me at this stage.
Any ideas or input would be highly appreciated.
Gracias!
Update: I managed to resolve the Angular error about the rootscope being thrown, but sadly, resolving that does not fix the main issue. If I tried to open the social login on the same browser tab where my application is, Google can login and return to the application and pass the tokens required. It is a different story for Facebook, where in the Developer's tools console, there is a warning that seems to stop Facebook from displaying the login page.
Pretty much, the original method with which a new window (or tab) is opened is the way forward but fixing the same for mobile browser seems to be getting more challenging.
On desktop, when the auth window pops up (not tab) it has the opener property set to the window which opened this pop up window, on mobile, as you said, its not a pop up window but a new tab. when a new tab is opened in the browser, the opener property is null so actually you have an exception here:
window.opener.$windowScope.authCompletedCB
because you can't refer the $windowScope property of the null value (window.opener) so every line of code after this one wont be executed - thats why the window isn't closed on mobile.
A Solution
In your authComplete.js file, instead of trying to call
window.opener.$windowScope.authCompletedCB and pass the fragment of the user, save the fragment in the localStorage or in a cookie (after all the page at authComplete.html is in the same origin as your application) using JSON.stringify() and just close the window using window.close().
In the loginController.js, make an $interval for something like 100ms to check for a value in the localStorage or in a cookie (don't forget to clear the interval when the $scope is $destroy), if afragment exist you can parse its value using JSON.parse from the storage, remove it from the storage and call $scope.authCompletedCB with the parsed value.
UPDATE - Added code samples
authComplete.js
...
var fragment = common.getFragment();
// window.location.hash = fragment.state || '';
// window.opener.$windowScope.authCompletedCB(fragment);
localStorage.setItem("auth_fragment", JSON.stringify(fragment))
window.close();
loginController.js
app.controller('loginController', ['$scope', '$interval', '$location', 'authService', 'ngAuthSettings',
function ($scope, $interval, $location, authService, ngAuthSettings) {
...
// check for fragment every 100ms
var _interval = $interval(_checkForFragment, 100);
function _checkForFragment() {
var fragment = localStorage.getItem("auth_fragment");
if(fragment && (fragment = JSON.parse(fragment))) {
// clear the fragment from the storage
localStorage.removeItem("auth_fragment");
// continue as usual
$scope.authCompletedCB(fragment);
// stop looking for fragmet
_clearInterval();
}
}
function _clearInterval() {
$interval.cancel(_interval);
}
$scope.$on("$destroy", function() {
// clear the interval when $scope is destroyed
_clearInterval();
});
}]);
I am trying to download a file from a FTP server using Cordova. I have ngCordova and the Filetransfer plugins installed. Below is my code:
angular.module('TestApp', ['ionic', 'TestApp.controllers', 'charts.ng.justgage', 'pascalprecht.translate', 'ngCookies', 'ngCordova'])
var app = angular.module('TestApp.controllers', [])
app.controller('FileDownloadCtrl', function($scope, $timeout, $cordovaFileTransfer) {
$scope.downloadFile = function() {
var url = "ftp://URL/somefile.xml";
var filename = url.split("/").pop();
alert(filename);
var targetPath = cordova.file.externalRootDirectory + filename;
var trustHosts = true;
var options = new Object();
var headers = { 'Authorization': 'Basic Login_cred' };
options.headers = headers;
alert(cordova.file.externalRootDirectory);
alert(options.headers);
$cordovaFileTransfer.download(url, targetPath, options, trustHosts)
.then(function(result) {
// Success!
alert(JSON.stringify(result));
}, function(error) {
// Error
alert(JSON.stringify(error));
}, function (progress) {
$timeout(function () {
$scope.downloadProgress = (progress.loaded / progress.total) * 100;
})
});
}
});
Angular.module is located in a different JS file in the actual code
This code returns the following alerts:
somefile.xml
file://storage/emulated/0/
[object Object]
{"code":2,"source":ftp://URL/somefile.xml","target":file:///storage/emulated/0/somefile.xml","http_status": null,"body":null,"exception":null}
I have tried downloading a file from a website hosted on the ftp (http://website/somefile.xml), which worked just fine. I am pretty sure I am doing something wrong with the header. I have also tried to put the Login_creds into the target url like this: ftp://username:password#URL/somefile.xml, this did not work but it could be browser specific.
ngCordova File Transfer does not work with ftp:// URL's, when I switched to a password protected http solution it worked.
Hi I have created a factory to get the current amount of users online from my Firebase database.
When I first load the page it works great and displays all the current users but then if I go to another page and come back it will display as 0 until a new user connects or disconnects or if I refresh.
I followed this guide:
http://www.ng-newsletter.com/advent2013/#!/day/9
App.js
angular.module('myApp', ['ngRoute', 'firebase', 'ui.bootstrap'])
.factory('PresenceService', ['$rootScope',
function($rootScope) {
var onlineUsers = 0;
// Create our references
var listRef = new Firebase('https://my-db.firebaseio.com/presence/');
// This creates a unique reference for each user
var onlineUserRef = listRef.push();
var presenceRef = new Firebase('https://my-db.firebaseio.com/.info/connected');
// Add ourselves to presence list when online.
presenceRef.on('value', function(snap) {
if (snap.val()) {
onlineUserRef.set(true);
// Remove ourselves when we disconnect.
onlineUserRef.onDisconnect().remove();
}
});
// Get the user count and notify the application
listRef.on('value', function(snap) {
onlineUsers = snap.numChildren();
$rootScope.$broadcast('onOnlineUser');
});
var getOnlineUserCount = function() {
return onlineUsers;
}
return {
getOnlineUserCount: getOnlineUserCount
}
}
]);
mainController.js
angular.module('myApp')
.controller('mainController', function($scope, authService, PresenceService, $http, $routeParams, $firebaseObject, $firebaseAuth, $location) {
$scope.totalViewers = 0;
$scope.$on('onOnlineUser', function() {
$scope.$apply(function() {
$scope.totalViewers = PresenceService.getOnlineUserCount();
});
});
// login section and auth
var ref = new Firebase("https://my-db.firebaseio.com");
$scope.authObj = $firebaseAuth(ref);
var authData = $scope.authObj.$getAuth();
if (authData) {
console.log("Logged in as:", authData.uid);
$location.path( "/user/"+authData.uid );
} else {
console.log("Logged out");
$location.path( "/" );
}
// user ref
var userRef = new Firebase("https://my-db.firebaseio.com/users/"+ authData.uid);
var syncObject = $firebaseObject(userRef);
syncObject.$bindTo($scope, "data");
});
main.html
{{totalViewers}}
Inside your controller, change yr first line as below.
//$scope.totalViewers = 0;
$scope.totalViewers = PresenceService.getOnlineUserCount();
Because each time you leave the page, its controller gets flushed and next time its getting value "zero". So, correctly you should read $scope.totalViewers from your service.
I have two views right now.
login
main
Right now I login and change my path to /main which works fine. When I am not logged in, and try to visit /main my web service returns "Access denied for user anonymous" which I then forward them to / which is my login view. How can I pass something so my LoginController knows they were forwarded from /main to alert them to login first?
LoginController.js
VforumJS.controller('LoginController', function($scope, $location, $routeParams, LoginModel)
{
$scope.email = "";
$scope.password = "";
$scope.fetching = false;
$scope.error = null;
$scope.login = function()
{
$scope.error = null;
$scope.fetching = true;
LoginModel.login($scope.email, $scope.password);
}
$scope.$on('LoginComplete', function(event, args)
{
log('login complete: ' + args.result);
$scope.fetching = false;
if (args.result == "success")
{
$location.path('/main');
}
else
{
$scope.error = args.result;
}
});
});
MainController.js
VforumJS.controller('MainController', function($scope, $location, $routeParams, MainModel)
{
$scope.currentTitle = '-1';
$scope.presentationData = MainModel.getPresentations();
$scope.$on('PresentationsLoaded', function(event, args)
{
log(args.result);
if (args.result != "Access denied for user anonymous")
{
//-- Parse preso data
$scope.presentationData = args.result;
}
else
{
//-- Need to login first, route them back to login screen
$location.path("/");
}
});
});
You can use $location.search() in your MainController to pass query string to the LoginController.
Inside you MainController:
if (args.result != "Access denied for user anonymous")
{
//-- Parse preso data
$scope.presentationData = args.result;
}
else
{
//-- Need to login first, route them back to login screen
$location.search({ redirectFrom: $location.path() });
$location.path("/");
}
And then in your LoginController, shortened for brevity:
VforumJS.controller('LoginController', function($scope, $location, $routeParams, LoginModel)
{
var queryString = $location.search();
$scope.$on('LoginComplete', function(event, args)
{
log('login complete: ' + args.result);
$scope.fetching = false;
if (args.result == "success")
{
if (queryString && queryString.redirectFrom) {
$location.path(queryString.redirectFrom);
} else {
$location.path('/somedefaultlocation');
}
}
else
{
$scope.error = args.result;
}
});
});
Alternatively you can use a shared service, maybe even your LoginModel to set a parameter from MainController to indicate the redirect came from it.
Update
Even better still, use $httpProvider.interceptors to register a response interceptor, and then use the same $location.search() technique described above to redirect to the login screen on authentication failure. This method is ideal as your controllers are then clean of authentication logic.
$location broadcasts $locationChangeStart and $locationChangeSuccess events, and the third param of each is oldUrl.
One solution would be to have a service that subscribes to $locationChangeStart in order to save the current and old urls.
When you hit /, your LoginController can check your service to see if the oldUrl is /main, and then act accordingly.