12

我是 angularJS 的初学者,我正在使用 node/bower/grunt 为 angularJS 中的单页应用程序开发 ui,并且我已经安装了 angular-ui-bootstrap 以及来自 angular-ui-utils 的路由和事件实用程序。
I've used ng-class={active:$uiRoute}on the menu items but when a menu item is selected the active class is not applied...does $uiRoutehandle this or do I need to code it separately?

抱歉问了一个愚蠢的问题......
这是代码:

`<div class="collapse navbar-collapse">
  <ul class="nav navbar-nav">
    <li ui-route="/" ng-class="{active:$uiRoute}"><a href="#/">Home</a></li>
    <li ui-route="/about" ng-class="{active:$uiRoute}"><a href="#/about">About</a></li>
    <li ui-route="/other" ng-class="{active:$uiRoute}"><a href="#/other">Other</a></li>
  </ul>
</div>
...
<script src="bower_components/angular-ui-utils/modules/route/route.js"></script>
<script src="bower_components/angular-ui-utils/modules/event/event.js"></script>`

angular.module('myApp', ['ngRoute','ngResource','ui.bootstrap'])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
    templateUrl: 'views/main.html',
    controller: 'MainCtrl'
  })
  .when('/about', {
      templateUrl: 'views/about.html',
      controller: 'AboutCtrl'
  })
  .when('/other', {
    templateUrl: 'views/other.html',
    controller: 'OtherCtrl'
  })
  .otherwise({
    redirectTo: '/'
  });
})
4

3 回答 3

2

查看ui-utils 文档,您似乎还没有注入模块依赖项。改变你myApp的注入ui.utils

angular.module('myApp', [
    'ngRoute',
    'ngResource',
    'ui.bootstrap',
    'ui.utils'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
    templateUrl: 'views/main.html',
    controller: 'MainCtrl'
  })
  .when('/about', {
      templateUrl: 'views/about.html',
      controller: 'AboutCtrl'
  })
  .when('/other', {
    templateUrl: 'views/other.html',
    controller: 'OtherCtrl'
  })
  .otherwise({
    redirectTo: '/'
  });
});
于 2015-04-21T23:52:01.850 回答
0
add ng-class="{'active':isActive('/about')}"

.run([ '$rootScope', '$location', function($rootScope, $location, ) {
    $rootScope.isActive = function(path) {
         if ($location.path() && $location.path().substring(0, path.length) == path) {
            return true;
         }
         return false;
    }
}
于 2016-07-02T11:35:25.670 回答
0

我建议你使用带有命名状态的 UI 路由器。

您的路由器将如下所示:

angular
  .module('myApp', ['ui.router'])
  .config(($stateProvider, urlRouterProvider) => {
    $stateProvider
      .state('index', {
        url: '/',
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
      })
      .state('index.about', {
        url: 'about/'
        templateUrl: 'views/about.html',
        controller: 'AboutCtrl'
      });
    $urlRouterProvider.otherwise('/');
  });

并且您将能够在模板中使用 ui-sref-active 指令,例如:

<div class="collapse navbar-collapse">
  <ul class="nav navbar-nav">
    <li ui-sref-active="{ 'active': 'index' }">
      <a href="" ui-sref="index">Home</a>
    </li>
    <li ui-sref-active="{ 'active': 'index.about' }">
      <a href="" ui-sref="index.about">About</a>
    </li>
  </ul>
</div>
于 2017-05-18T09:15:30.073 回答