【问题标题】:Redirecting in Angular using $window.location.href works if invoked directly, but not if called from another function如果直接调用,则使用 $window.location.href 在 Angular 中重定向有效,但如果从另一个函数调用则无效
【发布时间】:2015-03-06 20:33:48
【问题描述】:

我正在尝试从我的 Angular 应用程序重定向到非 Angular 页面。如果我在 $scope 上有一个重定向功能并通过 ng-click 直接从 UI 元素调用它,它会按预期工作。但是,如果我从另一个 $scope 函数中调用该函数,则页面会重新加载或保持原样。我怀疑这里存在范围界定问题,但我不知道它是什么。我也尝试了 $window.location.assign() 并得到了相同的结果。

为什么重定向以一种方式工作,而另一种则不行?谢谢!

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>

更新

dfsq 是对的,我的问题与 Angular 无关。我的应用程序是一个 .NET 应用程序,母版页上有一个表单。因为我使用的是 type=submit 的按钮,所以表单正在提交,这会取消重定向,除非您对其执行 preventDefault()。在我的调试中,我在标题元素上使用了 ng-click 函数来进行重定向。这很好用,因为它没有提交表单,但它也让我误以为这是一个范围界定问题。

【问题讨论】:

    标签: javascript .net angularjs


    【解决方案1】:

    这与 Angular 无关。包装重定向不起作用的原因是它使用了不同的重定向 URL(在reddit 域上)。此资源具有限制内容策略,阻止它在不同域页面的 iframe 中显示。

    Сorresponding 错误:

    拒绝在框架中显示“http://www.reddit.com/r/CrappyDesign”,因为它将“X-Frame-Options”设置为“SAMEORIGIN”。

    第一个目标 URL 没有此限制,因此可以完美运行。

    来自关于X-Frame-Options的文档:

    X-Frame-Options HTTP 响应标头可用于指示是否应允许浏览器以 、 或 呈现页面。网站可以使用它来避免点击劫持攻击,确保其内容不会嵌入到其他网站中。

    【讨论】:

    • 是有道理的,更新 Pen 可以使其正常工作。这可能意味着我没有重现我认为我在我的应用程序中遇到的问题,尽管我会继续努力。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-06-23
    • 2014-10-17
    • 2016-12-14
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    相关资源
    最近更新 更多