change state with ui-router when button is clicked

In my angular 1.4.X app, I change state in an <a> element via the ui-sref directive like so:

<a ui-sref="challenges.show({ challengeId: challenge.id })">Change state</a>

What is the equivalent syntax when using a button instead of a link

<button>Change state</button>

Upvotes: 1

Views: 2179

Answers (3)

Chris Stanley
Chris Stanley

Reputation: 2926

Why not just use a tag but style it as a button?

Upvotes: 0

Sravan
Sravan

Reputation: 18647

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';
});
<!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>
      
    </ul>
  </nav>


</body>

</html>

ui-sref can be binded to any clickable element

<button ui-sref="challenges.show({ challengeId: challenge.id })" class="btn btn-danger navbar-btn"> Schedule </button> 

Upvotes: 3

Pankaj Parkar
Pankaj Parkar

Reputation: 136154

ui-sref will be only available on anchor tag. If you use button, you have to call to action from controller.

<button 
  ng-click="go('challenges.show', { challengeId: challenge.id })">
     Change state
</button>

Controller

$scope.go = $state.go;

Upvotes: 0

Related Questions