这是一个运行良好的 plnkr 示例:http://plnkr.co/edit/p45udWaLov388ZB23DEA?p=preview
具有 2 个链接的导航(路由到 2 个 ui-router 状态),以及一个在事件链接上维护事件类的 jQuery 方法。
index.html
<body ng-app='myApp'>
<ul class="nav nav-pills">
<li role="presentation" class="active"><a ui-sref="home">Home</a></li>
<li role="presentation"><a ui-sref="news">News</a></li>
</ul>
<ui-view></ui-view>
</body>
app.js
angular.module('myApp', ['ui.router'])
.config(function($stateProvider){
$stateProvider.state('home', {
url : '/home',
template: '<h1>home</h1>'
});
$stateProvider.state('news', {
url : '/news',
template: '<h1>news</h1>'
});
});
script.js
$(document).ready(function(){
$(".nav a").on("click", function(){
$(".nav").find(".active").removeClass("active");
$(this).parent().addClass("active");
});
});
该应用程序工作正常,但尝试在浏览器导航器中手动输入网址时除外,例如,如果事件选项卡是主页,而我选择 http://localhost:8080/news/ 状态为新闻,但活跃类别仍在首页
最佳答案
如果您直接转到/news,您的函数永远不会执行。它仅在单击导航链接时执行。您希望在初始加载时以及状态更改时执行该函数。
更好的方法是完全避免 jQuery 并以“Angular 方式”执行操作。您可以为导航栏创建一个 Controller ,并在状态发生变化时在适当的元素上设置 active
类。
关于javascript - Bootstrap : maintaining active state based on routing when manually entering url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43022889/