简体   繁体   English

Angularjs在url更改时更改类名

[英]Angularjs changing class name on url change

I'm trying to add 'active' class to my menu items on url change. 我正在尝试在网址更改时为我的菜单项添加“活动”类。

This is what I've tried so far : JSFiddle 这是我到目前为止所尝试的: JSFiddle

(ps: I tried to use stack's code snippets but it doesn't seem to work) (ps:我尝试使用堆栈的代码片段,但它似乎不起作用)

HTML: HTML:

<div ng-app="townApp">
  <aside ng-controller="sideCtrl">
    <ul id="sidebar">
      <li ng-repeat="item in menuItems" ng-class="{'active': item.link == url}">
        <a href="{{ item.link }}" ng-click="activate(item);">
        <i class="glyphicon glyphicon-{{ item.icon }}"></i>
        {{ item.text | uppercase }}
        </a>            
      </li>
    </ul>
  </aside>
</div>

JS: JS:

var townApp = angular.module('townApp', []);

townApp.controller('sideCtrl', function($scope, $location){
  $scope.menuItems = [
    {text:"dashboard", link:"#/dashboard", icon:"tint"}, 
    {text:"payments", link:"#/payments", icon:"tint"}, 
    {text:"graphs", link:"#/graphs", icon:"tint"},
  ];
  $scope.url = '#' + $location.absUrl().split('/#')[1];
  $scope.activate = function(item){
    $scope.url = '#' + $location.absUrl().split('/#')[1];
  }
});

This is working good on my local machine's page load.(not on jsfiddle which seems reasonable) but the problem is when clicking on each menu item, 'active' class will be added to previous clicked item. 这在我的本地机器的页面加载上工作得很好。(不是在jsfiddle这看起来合理)但问题是当点击每个菜单项时,'active'类将被添加到之前点击的项目。

See the updated Fiddle . 查看更新的小提琴 The important change happened on these lines: 这些方面发生了重大变化:

$scope.activate = function(item){
    $scope.url = item.link;
}

Basically, the activate function is triggered before the URL is changed, that is why it was taking the URL of the previous item. 基本上,在更改URL之前触发activate函数,这就是它获取前一项的URL的原因。

An alternate solution would be to use $timeout ( Fiddle ) : 一种解决方案是使用$timeout 小提琴

$scope.activate = function(item){
  $timeout(function() {
    $scope.url = '#' + $location.absUrl().split('/#')[1];
  });
}

(Do not forget to inject $timeout into your controller in such case.) (在这种情况下,不要忘记向控制器注入$timeout 。)

You just need to use the item that you're passing in as the url hasn't changed yet: 您只需要使用您传入的项目,因为网址尚未更改:

    $scope.url = '#' + $location.absUrl().split('/#')[1];

    $scope.activate = function(item){
        $scope.url = item.link;
    }

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

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