Scott McD. Scott McD. - 1 year ago 128
Javascript Question

Redirecting in Angular using $window.location.href works if invoked directly, but not if called from another function

I'm trying to redirect from my Angular app to a non-angular page. If I have a redirect function on the $scope and invoke it directly from a UI element via ng-click it works as expected. If I call the function from within another $scope function, though, the page reloads or remains as is. I suspect there is a scoping issue here, but I can't tell what it is. I also tried $window.location.assign() and got the same result.

Why is the redirect working one way, but not the other? Thanks!

Link to CodePen



angular.module('myApp').controller('myCtrl', [ '$scope', '$window', function($scope, $window){
$scope.destination = "";
$scope.redirectStarted = false;

$scope.redirect = function(target){
$window.location.href = target;
$scope.redirectStarted = true;

$scope.wrapperFunction = function() {
var altDestination = "";


<div data-ng-app="myApp" data-ng-controller="myCtrl">
<li>Invoke redirect() directly: <input type="button" value="Direct Invocation" data-ng-click="redirect(destination)" /></li>
<li>Invoke from wrapper function: <input type="button" value="From Wrapper" data-ng-click="wrapperFunction()" /></li>
<div data-ng-show="redirectStarted">
Redirect started


dfsq was right that my problem was not related to Angular. My app is a .NET application, and there was a form on the master page. Because I was using a button of type=submit, the form was being submitted, which cancels the redirect unless you do a preventDefault() on it. In my debugging, I was using an ng-click function on a header element to do the redirect. That worked fine because it didn't submit the form, but it also led me down the wrong path in thinking it was a scoping problem.

Answer Source

This has nothing to do with Angular. The reason why the wrapper redirect is not working, is that it is using different redirect URL (on reddit domain). This resource has restricted content policy preventing it from being displayed in iframe on different domain pages.

–°orresponding error:

Refused to display '' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

The first destination URL doesn't have this limitation, so it works flawlessly.

From documentation about X-Frame-Options:

The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a , or . Sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download