我尝试使用AngularJS的jQuery Lite库为元素添加活动类,但我遇到了麻烦。
我希望我可以执行类似element.children()[index].addClass('active');
的操作,但是会返回以下错误:
TypeError: element.children(...)[index].addClass is not a function
有没有办法将类添加到元素的单个子元素中?
(function() {
'use strict';
angular
.module('rugapp')
.directive('menu', menu);
menu.$inject = ['$location'];
function menu($location) {
return {
restrict: 'A',
link: link
};
function link(scope, element) {
scope.$on('$routeChangeSuccess', function() {
angular.forEach(element.children(), function(link, index) {
if (link.hash.replace('#', '') === $location.path()) {
console.log("Make " + $location.path() + " active!!!");
console.log(element.children()[index]);
// element.children()[index].addClass('class');
}
});
});
}
}
})();
为完整起见,此指令的应用如下:
<div class="list-group" menu>
<a href="app/#/" class="list-group-item">Home</a>
<a href="app/#/link1" class="list-group-item">Link1</a>
<a href="app/#/link2" class="list-group-item">Link2</a>
....
</div>
更新:工作指令添加&#39;有效&#39;使用AngularJS指令的类。
(function() {
'use strict';
angular
.module('rugapp')
.directive('menu', menu);
menu.$inject = ['$location'];
function menu($location) {
return {
restrict: 'A',
link: link
};
function link(scope, element) {
scope.$on('$routeChangeSuccess', function() {
angular.forEach(element.children(), function(link, index) {
if (link.hash.replace('#', '') === $location.path()) {
element.children().eq(index).addClass('active');
} else {
element.children().eq(index).removeClass('active');
}
});
});
}
}
})();
答案 0 :(得分:3)
简单回答,你想要做的就是这个
element.children().eq(index).addClass('active');
请注意,eq()从零开始。所以选择第一个孩子,你最终得到这个
element.children().eq(0).addClass('active');
此处有更多信息:http://api.jquery.com/eq/
答案 1 :(得分:1)
枚举子DOM元素并查找/提取链接到不同&#34;路由的锚点的想法&#34; (我认为你在这里使用路线,虽然它并不重要)是非常易变的。更别说,假设(正如您的方法所示)只有 <a>
子元素。
如果您决定使用<button>
,该怎么办?如果您有其他非菜单相关<a>
或其他样式组件,该怎么办?对DOM的任何修改都会破坏您的方法。
相反,我建议你按照angular-ui
did with ui-sref-active
的做法(src)。它显然只与ui.router
一起使用,但这个想法是一样的:它应用了一个&#34; active&#34;基于匹配&#34;状态&#34;。
因此,您的概念解决方案可能是:
.directive("menuActive", function($location, $interpolate){
return {
restrict: "A",
link: function(scope, element, attrs){
var activeClass = $interpolate(attrs.menuActive)(scope);
// for simplicity of example, I assume that it only applies
// to <a href="url#hash">, but you could make it generic
if (element[0].tagName !== "A") return;
var link = element[0];
$scope.$on("$routeChangeSuccess", function()
if (link.hash.replace('#', '') === $location.path()){
element.addClass(activeClass);
} else {
element.removeClass(activeClass);
}
}
}
});
,用法是:
<div class="list-group">
<a href="app/#/" menu-active="active" class="list-group-item">Home</a>
<a href="app/#/link1" menu-active="active" class="list-group-item">Link1</a>
<a href="app/#/link2" menu-active="active" class="list-group-item">Link2</a>
....
</div>