Trigger state in button tag using ui-sref

HP. picture HP. · Mar 2, 2014 · Viewed 46.7k times · Source

What is the elegant way to trigger a state with angular-ui-router by clicking <button>?

I am using ui-sref="main" and it doesn't seem to work although it works with <a> though.

HTML:

<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <link data-require="[email protected]" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="[email protected]" src="http://code.angularjs.org/1.2.13/angular.js" data-semver="1.2.13"></script>
  <script src="http://angular-ui.github.io/ui-router/release/angular-ui-router.js" ></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">

  <nav class="navbar navbar-default">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">Brand</a>
    </div>  
    <ul class="nav navbar-nav navbar-left">
      <li>
        <button class="btn btn-danger navbar-btn" ui-sref="main" >Button Submit</button>
      </li>
      <li>
        <a class="btn btn-danger navbar-btn" ui-sref="main" >Anchor Link Submit</a>
      </li>
    </ul>
  </nav>


</body>

</html>

Javascript:

var app = angular.module('plunker', ['ui.router']);

'use strict';

app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {

  $stateProvider
    .state("main", {
      url: "/main",
      resolve: {
        test: function() {
          alert("Triggered main state");
          return true;
        }
      }
    });

}]);


app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
});

Link: http://plnkr.co/edit/vMtLN0ncpqAfgM6S1Ng4?p=preview

Answer

Alp picture Alp · May 11, 2014

Wrap the button in an anchor and you are good to go:

<a ui-sref="main">
    <button class="btn btn-danger navbar-btn" >Button Submit</button>
</a>

DEMO