Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use ng-click with ui-sref?

Can I do this?

<button ng-click='vm.foo()' ui-sref='state'>test</button>
like image 260
Adam Zerner Avatar asked Aug 24 '15 15:08

Adam Zerner


1 Answers

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="[email protected]" 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');
  }
}
like image 154
Adam Zerner Avatar answered Oct 14 '22 16:10

Adam Zerner