ui-router $state.go VS ui-sref is making me nuts i

2019-06-08 14:33发布

问题:

It works when called via ui-sref

<a class="button" ui-sref="main.create">

but when it's called using ng-click and $stage.go, it's called and renders the page but my $urlRouterProvider.otherwise will override the DOM again. I noticed it when I debugged step by step. It maybe thinks that main.create is a non-existent url.

here is the code and function for ng-click.

<a href="#" ng-click="create()">Create Object</a>

and here is create() function

$scope.create = function() {
  $state.go('main.create');
};

It's calling $state.go('main') when ng-click="create()" is used. But before it calls $state.go('main'), I see the proper main.create page render in DOM. I wrote that "IF" statement to handle non-existent url so they get redirected back to main page. Here is my config.js.

  .state('main', {
    url: '/',
    views: {
      '@': {
        templateUrl: 'app/main/main.html',
        controller: 'MainController'
      },
      'content@main' : {
        templateUrl: 'app/main/main.display.html'
      }
    }
  })

  .state('main.create', {
    url: '/create',
    views: {
      'content@main' : {
        templateUrl: 'app/main/main.create.html'
      }
    }
  })

  $urlRouterProvider.otherwise(function ($injector) {
  var Session = $injector.get('Session');
  var $state = $injector.get('$state');
  if (Session.isAuthenticated()) {
    $state.go('main'); // <-- this is what gets called when using ng-click and after main.create partial gets rendered
  } else {
    $state.go('login');
  }
});

回答1:

This is occurring because you are triggering an action and a route on the same anchor tag. In <a href="#" ng-click="create()">, you don't need both href and ng-click to be present. change it to <a ng-click="create()">, or if having the href is necessary, set it to empty, like <a href="" ng-click="create()">.



回答2:

Claies is correct that the problem is stemming from having both an href and an ng-click on the same tag, but the proper solution is to make sure your $scope.create() function returns a false boolean value immediately after the call to $state.go, then the href can be whatever you want and will get ignored.

In general (even outside angular), if an anchor tag has both an href and a click event handler, it will execute both of them, first the click event handler(s), then the href -- unless the click event handler returns a false value, then it effectively cancels the href execution. As you noted, the different browsers execute href="#" and/or href="" differently, but it won't be an issue if your $scope.create() function returns false.