【问题标题】:AngularJS ReferenceError: $window is not definedAngularJS ReferenceError: $window 未定义
【发布时间】:2014-06-17 01:07:29
【问题描述】:

如果我的用户通过了我的表单验证(根据数据库值检查用户名和密码),我会尝试重定向他们。

验证工作正常,但在我的 .Success 函数中,重定向似乎不起作用,它产生错误:'ReferenceError: $window is not defined'。

代码如下:

.success(function(data) {
    console.log(data);

        if (!data.success) {
            // if not successful, bind errors to error variables
            $scope.errorUserName = data.errors.userName;
            $scope.errorUserPassword = data.errors.userPassword;
        } else {
            // if successful, bind success message to message
            $scope.message = data.message;
            $window.location=('twitter.com');       
    }
});

我已尝试更改位置路径,但似乎没有任何效果。有什么想法吗?

谢谢!

懒人龙猫

【问题讨论】:

  • Twitter.com 只是一个占位符! :)

标签: javascript angularjs validation redirect window


【解决方案1】:

$window需要注入。

要注入它,您只需将其作为参数添加到控制器函数中,Angular 会自动处理其余部分。

例如:

app.controller('MyController', function MyController($scope, $window) {

    $window.location = 'http://stackoverflow.com'
});

您可以在 AngularJS here 中阅读有关依赖注入的更多信息。

如果您不需要重新加载整个页面,则应该注入并使用$location

// get the current path
$location.path();

// change the path
$location.path('/newValue');

【讨论】:

  • 谢谢!我刚刚尝试了“document.location.href=''”,它也有效! :D
  • 是的,但是在哪里注入?
  • 对于新手来说不是一个完整的答案...注入在哪里,如何将控制器变量与控制器函数内的变量链接起来?!
  • @Serge 记笔记并进行了小幅编辑。现在好点了?但是请注意,这不应该作为依赖注入如何工作的指南,尽管答案当然应该尽可能有帮助。
猜你喜欢
  • 2015-08-26
  • 2012-11-25
  • 2016-07-07
  • 1970-01-01
  • 2016-05-09
  • 2020-12-26
  • 1970-01-01
  • 2017-02-18
  • 2023-04-04
相关资源
最近更新 更多