我的路线档案
app.config(["$routeProvider",function($route)
{
$route.when("/",{
templateUrl : "partials/index.html",
controller : "AppCtrl"
}).when("/contact",{
templateUrl:"partials/contact.html",
controller:"ContactCtrl"
}).
when("/about-us",{
templateUrl:"partials/about.html",
controller:"AboutCtrl"
}).
when("/gallery",{
templateUrl:"partials/gallery.html",
controller:"GalleryCtrl"
}).
otherwise({
redirectTo:"/"
});
}]);
在我的header.html部分中我正在使用HeaderCtrl控制器
app.controller("HeaderCtrl",["$scope","$location",function($scope,$location)
{
$scope.location=$location.path().replace("/","");
}]);
我的header.html
<ul ng-controller="HeaderCtrl">
<li ng-class="{active:location===''}"><a href="#">home</a></li>
<li ng-class="{active:location==='about-us'}"><a href="#/about-us">about us</a></li>
<li ng-class="{active:location==='gallery'}"><a href="#/gallery">gallery</a></li>
<li ng-class="{active:location==='contact'}"><a href="#/contact">contact</a></li>
</ul>
当页面重新加载(实际刷新)然后它工作,即类激活应用于相应的li但是当我更改路线(通过单击菜单项)它不起作用
答案 0 :(得分:2)
您的问题的解决方案是在URL成功更改时绑定更新$scope.location
的事件。您不必将点击事件绑定到每个<li>
元素。如果路线无效或失败怎么办?您并不希望向用户显示该元素是非活动路线,但实际上并非如此。
如果您阅读$location
服务上的documentation,则会看到活动部分。我们感兴趣的是$locationChangeSuccess
。要在控制器中连接它,请执行以下操作:
$scope.$on('$locationChangeSuccess', function () {
$scope.location = $location.path().replace('/', '');
});
答案 1 :(得分:0)
您向路由器添加了诸如active之类的对象,并使用ngClass在html上设置了条件
像这样:
app.config(["$routeProvider",function($route)
{
$route.when("/",{
templateUrl : "partials/index.html",
controller : "AppCtrl",
active:'home',
}).when("/contact",{
templateUrl:"partials/contact.html",
controller:"ContactCtrl",
active:'contact',
}).
when("/about-us",{
templateUrl:"partials/about.html",
controller:"AboutCtrl",
active:'about',
}).
when("/gallery",{
templateUrl:"partials/gallery.html",
controller:"GalleryCtrl"
active:'GalleryCtrl',
}).
otherwise({
redirectTo:"/"
});
}])
//remember that add $route inside the scope
.controller("HeaderCtrl",["$scope","$location",function($scope,$route)
{
$scope.$route = $route;
}]);
.active{
color:#a33;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<ul ng-controller="HeaderCtrl">
<li data-ng-class="{'active':$route.current.active === 'home'}"><a href="#">home</a></li>
<li data-ng-class="{'active':$route.current.active === 'about'}"><a href="#/about-us">about us</a></li>
<li data-ng-class="{'active':$route.current.active === 'gallery'}"><a href="#/gallery">gallery</a></li>
<li data-ng-class="{'active':$route.current.active === 'contact'}"><a href="#/contact">contact</a></li>
</ul>