Siddharth Srivastva
Siddharth Srivastva

Reputation: 965

$window.location.href not working

I was always using this but I don't know why this is not working. I have put ng-click="login()" on button and inside controller HTML:

<div class="login-wrapper" ng-controller="loginCtrl">
    <div ng-show="showAlert" class="alert alert-warning alert-bold-border fade in alert-dismissable">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
        <strong>{{alert.head}}</strong> {{alert.body}}
    </div>
    <form role="form">
        <div class="form-group has-feedback lg left-feedback no-label">
            <input type="text" class="form-control no-border input-lg rounded" placeholder="Enter username" autofocus ng-model="user.name">
            <span class="fa fa-user form-control-feedback"></span>
        </div>
        <div class="form-group has-feedback lg left-feedback no-label">
            <input type="password" class="form-control no-border input-lg rounded" placeholder="Enter password" ng-model="user.password">
            <span class="fa fa-unlock-alt form-control-feedback"></span>
        </div>
        <div class="form-group">
            <button type="submit" class="btn btn-warning btn-lg btn-perspective btn-block" ng-click="login()">LOGIN</button>
        </div>
    </form>
</div>

JS

App.controller("loginCtrl", function ($scope, $rootScope, $window) {
    $scope.showAlert = false;
    $scope.login = function () {

        console.log("sid");
        $scope.showAlert = false;
        $window.location.href = "http://www.google.com";
    };
});

But the page reloads instead of going anywhere and I am seeing on log sid, so the function call is happening.

Strange. Could you please guide me?

Upvotes: 0

Views: 369

Answers (2)

Brian
Brian

Reputation: 156

I don't think you need $window in this case. Try without the $ like so:

App.controller("loginCtrl", function ($scope, $rootScope) {
$scope.showAlert = false;
$scope.login = function () {


    console.log("sid");
    $scope.showAlert = false;
    window.location.href = "http://www.google.com";
    };
});

Upvotes: 2

James
James

Reputation: 1514

I can't give you a great answer without a look at your html but it seems like to me whatever item has the ng-click="login()" it seems like the browser is still submitting the form when the button is clicked. I would suggest loading in the $event and do a $event.preventDefault(); inside your login function.

Note you could also add a return false; to the bottom of the function but I think that is a little sloppier then just injecting $event into the function and preventing it.

Upvotes: 0

Related Questions