单击按钮时使用ui-router更改状态

时间:2016-10-20 14:56:09

标签: angularjs

在我的角度1.4.X应用中,我通过<a>指令更改ui-sref元素中的状态,如下所示:

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

使用按钮而不是链接

时的等效语法是什么
<button>Change state</button>

3 个答案:

答案 0 :(得分:3)

&#13;
&#13;
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';
});
&#13;
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <link data-require="bootstrap-css@3.1.1" 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="angular.js@1.2.x" 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>
&#13;
&#13;
&#13;

ui-sref可绑定到任何可点击元素

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

答案 1 :(得分:0)

ui-sref仅适用于锚标记。如果您使用button,则必须从控制器调用操作。

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

<强>控制器

$scope.go = $state.go;

答案 2 :(得分:0)

为什么不使用a标签,而是将其设为按钮?