Can you use ng-click with ui-sref?

2020-03-01 04:22发布

Can I do this?

<button ng-click='vm.foo()' ui-sref='state'>test</button>

1条回答
一夜七次
2楼-- · 2020-03-01 05:04

Yes. ngClick will run, and then you'll transition to your state.

Demo (updated and working thanks to marioosh)

However, if you have an $event.preventDefault() in ngClick, it won't transition you to your state.

Full code example

<!DOCTYPE html>
<html ng-app='app'>

  <head>
    <script data-require="angular.js@1.4.3" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular.js"></script>
    <script data-require="ui-router@*" data-semver="0.2.15" src="//rawgit.com/angular-ui/ui-router/0.2.15/release/angular-ui-router.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller='MainController as vm'>
    <ul>
      <li><a ui-sref='home'>home</a></li>
      <li><a ui-sref='one' ng-click='vm.test()'>one</a></li>
      <li><a ui-sref='two'>two</a></li>
    </ul>
    <div ui-view></div>
  </body>

</html>

angular
  .module('app', ['ui.router'])
  .config(config)
  .controller('MainController', MainController)
;

function config($locationProvider, $urlRouterProvider, $stateProvider) {
  $urlRouterProvider.otherwise('/');
  $stateProvider
    .state('home', {
      url: '/',
      templateUrl: 'home.html'
    })
    .state('one', {
      url: '/one',
      templateUrl: 'one.html'
    })
    .state('two', {
      url: '/two',
      templateUrl: 'two.html'
    })
  ;
}

function MainController($scope) {
  var vm = this;
  vm.test = function() {
    alert('test');
    console.log('test');
  }
}
查看更多
登录 后发表回答