简体   繁体   English

ng-class条件有效,但仅当我刷新页面时

[英]ng-class condition works, but only when I refresh the page

I have a directive for Navigation; 我有一个导航指令; which is working fine... except when I change the page the class "active" is not getting added to the relevant link until I manually refresh the website. 效果很好...除非我更改页面,否则在手动刷新网站之前,不会将“活动”类添加到相关链接。

The code where my ng-class is in : 我的ng-class所在的代码:

<ul class="nav navbar-nav">
   <li ng-repeat="item in nav" ng-class="{'active':(item.alias==current)}">
      <a ui-sref="{{item.alias}}">{{item.name}}</a>
   </li>
</ul>

Navigation Directive: 导航指令:

(function () {
    'use strict';
    angular
        .module('app')
        .directive('navigation', navigation);

    navigation.$inject = ['$rootScope', '$timeout', '$state', 'navService'];

    function navigation($rootScope,$timeout, $state, navService) {

        $rootScope.nav = navService.nav;
        $rootScope.current = $state.current.name;

        return {
            restrict: 'AE',
            replace: 'true',
            templateUrl: '/layout/navigation/navigation.html'
        };

    };
})();

I was under the impression that this should work out of the box! 我的印象是,这应该开箱即用! Is it because I'm using the directive? 是因为我正在使用指令吗?

Most likely -not sure which version you are using, but...- you can use the ui-sref-active attribute in ui-router for this. 最有可能-不确定使用的是哪个版本,但是...-您可以为此使用ui-router中的ui-sref-active属性。

<ul class="nav navbar-nav">
   <li ng-repeat="item in nav" ui-sref-active="active">
      <a ui-sref="{{item.alias}}">{{item.name}}</a>
   </li>
</ul>

Your navigation function runs only once when page loads. navigation功能在页面加载时仅运行一次。 And $rootScope.current is set only once. $rootScope.current仅设置一次。 Looks like you are using ui-router. 看起来您正在使用ui-router。 Try to put that line in $stateChangeSuccess event callback: 尝试将该行放入$stateChangeSuccess事件回调中:

$rootScope.$on('$stateChangeSuccess', 
  function(event, toState, toParams, fromState, fromParams) {
    $rootScope.current = toState.name;
  }
)

Instead of keeping track of the current state name in the $rootScope why not check the state name directly like this. 与其在$ rootScope中跟踪当前状态名称,不如直接检查这种状态名称。

ng-class="{ 'active': $state.includes('state.name')}"

This should work for nested states too. 这也应该适用于嵌套状态。 For example if your states look like below then $state.includes('home.item1') will be true if the state is subItem1 例如,如果你的状态看起来像下面然后$state.includes('home.item1')如果状态将是真正subItem1

home
    item1
        subItem1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM