AngularJS ReferenceError:未定义$ window

时间:2014-04-30 15:53:54

标签: javascript angularjs validation redirect window

如果用户通过表单验证(根据数据库值检查用户名和密码),我会尝试重新指导用户。

验证工作正常但在我的.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');       
    }
});

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

谢谢!

LazyTotoro

1 个答案:

答案 0 :(得分:45)

$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');
相关问题