how to redirect using ng-click

Few things to note here:

  1. Referencing the Window in Angular expressions is disallowed!, so trying to use $window.location.href = '/url' on an inline ng-click expression will not work.
  2. $location is not exposed automatically to your scope, you'll need to expose this to the view by injecting it first to the controller and then the scope.

    .controller('LoginCtrl', function($scope, $location) { $scope.$loc = $location; })

  3. It's worth noting that $location.path() & $location.url() will NOT redirect you to a new page, this is used for routing so that route callbacks/watchers can do it's thing. The $location service allows you to change only the URL; it does not allow you to reload the page.

  4. The best (and also angular way imo) is to add a method to your scope in the controller. When you need to change the URL and reload the page or navigate to a different page, please use a lower level API: $window.location.href.

Use a method bound to your controller:

$scope.redirect = function(url, refresh) {
    if(refresh || $scope.$$phase) {
        $window.location.href = url;
    } else {
        $location.path(url);
        $scope.$apply();
    }
}

And then call your method from your ng-click expression:

<button ng-click="redirect('/')">GO HOME! NO BODY LOVES YOU</button>

Note: The above method will require you to inject both $location & $window to your controller.


Put a method on your controller to do the redirect and have that called form the ng-click on your button.

Markup:

<button ng-click="goLogin()">Log in</button>

Controller:

.controller('LoginCtrl', function($scope, $location) {
    $scope.form = {
        username: null,
        password: null
    };

    $scope.goLogin = function() {
        $location.url('http://test.com/login.jsp?un='+ $scope.form.username +'&pw="+ $scope.form.password);
    };
})

Also note you want to call $location.url() not path()

OR...

Add $location to your scope and call url({{newUrl}}):

$controller('MyCtrl', function($scope, $location) {
    $scope.$location = $location;
})

I'd still go with calling method on the scope.