AngularJS ReferenceError: $window is not defined

All we need is an easy explanation of the problem, so here it is.

I’m trying to re-direct my users if they pass my form validation (checking usernames and passwords against database values).

The validation works fine but in my .Success function the redirect doesn’t seem to be working, it produces the error: ‘ReferenceError: $window is not defined’.

Here’s the code:

.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');       
    }
});

I’ve tried changing the location path but nothing seems to be working. Any ideas?

Thanks!

LazyTotoro

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

$window needs to be injected.

To inject it you simply add it as a parameter to your controller function and Angular will automatically take care of the rest.

For example:

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

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

You can read more about dependency injection in AngularJS here.

If you don’t need a full page reload you should instead inject and use $location:

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

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

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply