AngularJS参考错误:$window未定义。

23

我试图在通过表单验证后重定向我的用户(检查用户名和密码是否与数据库值匹配)。

验证可以正常工作,但在我的 .Success 函数中,重定向似乎没有起作用,它会产生错误:“ReferenceError: $window 未定义”。

以下是代码:

.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只是一个占位符! :) - user3350593
1个回答

46

$window需要被注入。

注入它很简单,只需将它作为参数添加到您的控制器函数中,Angular会自动处理剩下的部分。

例如:

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

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

你可以在这里阅读关于AngularJS依赖注入的更多信息

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

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

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

1
谢谢!我刚试了 "document.location.href= ''",也可以工作啊! :D - user3350593
1
是的,但是注入到哪里? - Coastal-Cam
不是针对新手的完整答案... 注入在哪里,如何将控制器变量与控制器函数内部的变量链接起来?! - serge
@Serge 已经记录并进行了小的编辑。现在好了吗?请注意,这不应该是一个关于依赖注入如何工作的指南,尽管答案当然应该尽可能有帮助性。 - tasseKATT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接