ui-sref-active vs $ state.includes()

时间:2017-05-19 10:08:34

标签: javascript angularjs angular-ui-router

在这里,我试图通过使用ui-sref-active$state.includes()添加活动课来突出显示所点击的区域,但是它不能与$state.includes()一起使用,但是我得到的值是真的我通过控制器看到它的价值。帮助我。

以下是代码段:

var app = angular.module('myApp', ['ui.router']);
app.controller('myCtrl', function($scope,$state) {
$scope.res=$state.includes('')
});
app.config(function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('page');
    $stateProvider
      .state('page', {
        url: '/page',
        template: "u clicked on Luffy"
      })
      .state('paper', {
        url: '/paper',
        template: "u clicked on Zoro"
      })

  })
.active {
      background-color: red;
      color: white;
    }
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>

<body>
  <div ng-app="myApp" ng-controller="myCtrl">
    <hr>
    <h2>with ui-sref-active</h2>
    <button ui-sref-active=active ui-sref='page'>Luffy</button>
    <button ui-sref-active=active ui-sref='paper'>Zoro</button>
    <hr>
    <h2>with {'active':$state.includes('')}</h2>
    <button ng-class="{'active':$state.includes('page')}" ui-sref='page'>Luffy</button>
    <button ng-class="{'active':$state.includes('paper')}" ui-sref='paper'>Zoro</button>
    <hr> Result=
    <ui-view></ui-view>
    <hr>
  </div>
</body>

</html>

1 个答案:

答案 0 :(得分:3)

$state无法通过HTML访问,您可以在控制器中调用函数来实现此目的

&#13;
&#13;
var app = angular.module('myApp', ['ui.router']);
app.controller('myCtrl', function($scope,$state) {
  $scope.res = $state.includes('');
  $scope.checkActive = function(state) {
    return $state.includes(state)
  }
});
app.config(function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('page');
    $stateProvider
      .state('page', {
        url: '/page',
        template: "u clicked on Luffy"
      })
      .state('paper', {
        url: '/paper',
        template: "u clicked on Zoro"
      })

  })
&#13;
.active {
      background-color: red;
      color: white;
    }
&#13;
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>

<body>
  <div ng-app="myApp" ng-controller="myCtrl">
    <hr>
    <h2>with ui-sref-active</h2>
    <button ui-sref-active=active ui-sref='page'>Luffy</button>
    <button ui-sref-active=active ui-sref='paper'>Zoro</button>
    <hr>
    <h2>with {'active':$state.includes('')}</h2>
    <button ng-class="{'active':checkActive('page')}" ui-sref='page'>Luffy</button>
    <button ng-class="{'active':checkActive('paper')}" ui-sref='paper'>Zoro</button>
    <hr> Result=
    <ui-view></ui-view>
    <hr>
  </div>
</body>

</html>
&#13;
&#13;
&#13;