Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger state in button tag using ui-sref

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

like image 394
HP. Avatar asked Mar 02 '14 06:03

HP.


2 Answers

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

like image 151
Alp Avatar answered Oct 19 '22 02:10

Alp


the other solutions didn't work for me. Here's what I did using ui-router:

    <button ui-sref="app.schedule" class="btn btn-danger navbar-btn">
      Schedule
    </button>

Piece of pie :-)

like image 44
Michael Cole Avatar answered Oct 19 '22 01:10

Michael Cole