根据 Pavel 关于使用自定义指令的建议,这里有一个版本,它不需要向 routeConfig 添加任何有效负载,是超级声明性的,并且可以通过简单地改变你所关注的 slice()来适应路径的任何级别。
app.directive('detectActiveTab', function ($location) {
return {
link: function postLink(scope, element, attrs) {
scope.$on("$routeChangeSuccess", function (event, current, previous) {
/*
Designed for full re-usability at any path, any level, by using
data from attrs. Declare like this:
<li class="nav_tab">
<a href="#/home" detect-active-tab="1">HOME</a>
</li>
*/
// This var grabs the tab-level off the attribute, or defaults to 1
var pathLevel = attrs.detectActiveTab || 1,
// This var finds what the path is at the level specified
pathToCheck = $location.path().split('/')[pathLevel] ||
"current $location.path doesn't reach this level",
// This var finds grabs the same level of the href attribute
tabLink = attrs.href.split('/')[pathLevel] ||
"href doesn't include this level";
// Above, we use the logical 'or' operator to provide a default value
// in cases where 'undefined' would otherwise be returned.
// This prevents cases where undefined===undefined,
// possibly causing multiple tabs to be 'active'.
// now compare the two:
if (pathToCheck === tabLink) {
element.addClass("active");
}
else {
element.removeClass("active");
}
});
}
};
});
app.directive('activeTab', function ($location) {
return {
link: function postLink(scope, element, attrs) {
scope.$on("$routeChangeSuccess", function (event, current, previous) {
/* designed for full re-usability at any path, any level, by using
data from attrs
declare like this: <li class="nav_tab"><a href="#/home"
active-tab="1">HOME</a></li>
*/
if(attrs.href!=undefined){// this directive is called twice for some reason
// this var grabs the tab-level off the attribute, or defaults to 1
var pathLevel = attrs.activeTab || 1,
// this var finds what the path is at the level specified
pathToCheck = $location.path().split('/')[pathLevel],
// this var finds grabs the same level of the href attribute
tabLink = attrs.href.split('/')[pathLevel];
// now compare the two:
if (pathToCheck === tabLink) {
element.parent().addClass("active");//parent to get the <li>
}
else {
element.parent().removeClass("active");
}
}
});
}
};
});
我添加了“ if (attrs.href! = unDefinition)”,因为这个函数被学习调用两次,第二次会产生一个错误。
下面是 XMLillies w/domi 的 LI 更改的另一个版本,它使用搜索字符串而不是路径级别。我认为在我的用例中发生的情况更加明显。
statsApp.directive('activeTab', function ($location) {
return {
link: function postLink(scope, element, attrs) {
scope.$on("$routeChangeSuccess", function (event, current, previous) {
if (attrs.href!=undefined) { // this directive is called twice for some reason
// The activeTab attribute should contain a path search string to match on.
// I.e. <li><a href="#/nested/section1/partial" activeTab="/section1">First Partial</a></li>
if ($location.path().indexOf(attrs.activeTab) >= 0) {
element.parent().addClass("active");//parent to get the <li>
} else {
element.parent().removeClass("active");
}
}
});
}
};
});