how to redirect using ng-click

后端 未结 3 1299
我在风中等你
我在风中等你 2021-01-02 10:08

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 th

相关标签:
3条回答
  • 2021-01-02 10:30

    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.

    0 讨论(0)
  • 2021-01-02 10:47

    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>
    
    0 讨论(0)
  • 2021-01-02 10:50

    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.

    0 讨论(0)
提交回复
热议问题