Adam Zerner Adam Zerner - 1 month ago 36
AngularJS Question

Can you use ng-click with ui-sref?

Can I do this?

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

Answer

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

Demo

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>