Red-Beard Red-Beard - 1 year ago 80
AngularJS Question

how to redirect using ng-click

Super-simple AngularJS app I'm trying to build, to accept credentials into two text boxes, then use two-way binding to redirect on a button click to a url which includes the two variables in it.

My problem is, I can get it working for a simple

<a href=...>

(or maybe ng-href=...) but for some reason, no matter what I do, I can't get a redirect using a


I've tried a lot of variations, but here's what I'm trying to do

<button ng-click="$location.path('{{username}}&pw={{password}}')" class="btn btn-lg btn-warning">Log In!</button>

I CAN get it working if I call a function in a controller, but this is such a simple thing, I'd like to get it done on the page if possible.

Also, as a side-question, what are the security concerns of logging into a site like this?

Edit: The part that confuses me is, this works (just without two-way binding working):

<button onClick="'{{username}}');">

I'd expect that changing onClick to ng-click would give me the same behaviour, but with two-way binding.

**Re-Edit / Solution
Alright, so I finally got a workable solution.

I have NO idea why the Button tag won't work to give this behaviour, as stated above, but here's the working code.

<a href="{{username}}&pw={{password}}" class="btn btn-lg btn-warning">Log In!</a>

By giving it the same class as I intended to use for the button, the text shows up looking like a button, just the same.

Answer Source

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


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


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

    $scope.goLogin = function() {
        $location.url(''+ $scope.form.username +'&pw="+ $scope.form.password);

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


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.