Scott McD. Scott McD. - 4 months ago 39
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

JS

angular.module('myApp',[]);

angular.module('myApp').controller('myCtrl', [ '$scope', '$window', function($scope, $window){
$scope.destination = "http://www.clientsfromhell.net";
$scope.redirectStarted = false;

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

$scope.wrapperFunction = function() {
var altDestination = "http://www.reddit.com/r/CrappyDesign";
$scope.redirect(altDestination);
};
}]);


HTML

<div data-ng-app="myApp" data-ng-controller="myCtrl">
<ul>
<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>
</ul>
<div data-ng-show="redirectStarted">
Redirect started
</div>
</div>


UPDATE

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

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 'http://www.reddit.com/r/CrappyDesign' 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.

Comments