Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

<button>

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

<button ng-click="$location.path('http://example.com/login.jsp?un={{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="window.open('http://www.example.com/{{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="https://www.example.com/login.jsp?un={{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.

like image 829
Red-Beard Avatar asked Jul 24 '14 17:07

Red-Beard


2 Answers

you can also use ng-href.

<button ng-href="http://example.com/login.jsp?un={{username}}&pw={{password}}" class="btn btn-lg btn-warning">Log In!</button>
like image 165
user2909250 Avatar answered Oct 10 '22 02:10

user2909250


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.

like image 29
craigb Avatar answered Oct 10 '22 00:10

craigb