AngularJS ReferenceError: $window is not defined

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

$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');


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   How to hide element using Twitter Bootstrap and show it using jQuery?

Similar Posts