如何更新AngularJS指令时,URL被改变了吗? [英] How to update AngularJS directive when URL is changed?
问题描述
可能重复:
设置活动标签风格AngularJS
我用AngularJS并尝试添加一个当前类,以我的菜单时所显示的选项卡的内容。这是我迄今为止,它在加载页面时正常工作:
I'm using AngularJS and trying to add a "current" class to my menu whenever that tab's content is being displayed. This is what I have so far, and it works fine when loading the page:
HTML:
<ul id="nav">
<li><a href="#/one" class="highlighttab">One</a></li>
<li><a href="#/two" class="highlighttab">Two</a></li>
</ul>
记者:
myModule.directive('highlighttab', function($location) {
var currentPath = "#" + $location.path();
return {
restrict: 'C',
link: function(scope, element, attrs) {
var href = element.attr("href");
if (currentPath == href)
{
element.addClass("current");
}
}
};
});
这将添加当前类以正确的&LT; A&GT;
标记时,网页的网址是#/一个
或 /#两个
This will add the 'current' class to the correct <a>
tag when the page url is #/one
or /#two
现在的问题是,如果我点击第二个选项卡,类没有得到添加到它。我想我需要一些方法来获取code指令里面重新运行的URL发生变化时。有没有办法做到这一点?
The problem is if I click the second tab, the class does not get added to it. I imagine I need some way to get the code inside the directive to be re-run when the URL changes. Is there any way to do that ?
推荐答案
使用kfis的code从的http://计算器。 COM / A /一百六十八万四千八百六十分之一千二百六十三万一千二百一十四在评论中,我有这个现在用$ scope.watch上location.path工作()。
Using kfis's code from http://stackoverflow.com/a/12631214/1684860 in the comments, I have this working now using $scope.watch on location.path() .
myModule.directive('highlighttab', ['$location', function(location) {
return {
restrict: 'C',
link: function($scope, $element, $attrs) {
var elementPath = $attrs.href.substring(1);
$scope.$location = location;
$scope.$watch('$location.path()', function(locationPath) {
(elementPath === locationPath) ? $element.addClass("current") : $element.removeClass("current");
});
}
};
}]);
这篇关于如何更新AngularJS指令时,URL被改变了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!