当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > AngualrJS中的Directive制作一个菜单

AngualrJS中的Directive制作一个菜单

2018年06月17日  | 移动技术网IT编程  | 我要评论

说下我经常写菜单的方式:

<ul>
<li data-ng-class="{'active': highlight('/orders')}">
<a href="#/orders">orders</a>
</li>
</ul> 

菜单项是否高亮显示取决于controller中的highlight方法。

vm.highlight = funciton(path){
return $locaiton.path().substr(0, path.lenght) === path;
}

如果以directive的方式会更简洁。

<ul menu-highlighter highlight-class-name="active">
<li><a href="#/customers">customers</a></li>
<li><a href="#/orders">customers</a></li>
<li><a href="#/about">customers</a></li>
</ul> 

directive大致是:

(function(){
var injectparams = ['$location'];
var menuhighlighter = function($location){
var link = function(scope, element){
function setactive(){
var path = $location.path();
var classname = scope.highlightclassname || 'active';
if(path){
angular.foreac(element.find('li'), function(li){
//<a href="#/customers">customers</a>
var anchor = li.queryselector('a');
//#/customers
var href=(anchor && anchor.href) ? anchor.href : anchor.getattribute('data-href').replace('#','');
//customers
var trimmedhref = href.substr(href.indexof('#/')+1, href.length);
var basepath = path.substr(0, trimmedhref.length);
if(trimmedhref === basepath){
angular.element(li).addclass(classname);
} else {
angular.element(li).removeclass(classname);
}
});
} 
}
setactive();
scope.$on('$locationchangesuccess', setactive);
};
return {
restrict: 'a',
scope: {
highlightclassname: '@'
},
link: link
}
};
menuhighlighter.$inject = injectparams;
angular.module('my.directives')
.directive('menuhighlighter', menuhighlighter);
}()); 

以上内容是针对angualrjs中的directive制作一个菜单的相关知识,希望对大家有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网