นี่เป็นอีกแนวทางในการเน้นลิงค์ที่ใช้งานอยู่
คุณสมบัติหลัก:
- ทำงานได้ดีกับ href ที่มีนิพจน์เชิงมุมแบบไดนามิก
- เข้ากันได้กับระบบนำทางแบบแฮชแบง
- เข้ากันได้กับ Bootstrap โดยที่คลาสที่แอ็คทีฟควรถูกนำไปใช้กับพาเรนต์ li ไม่ใช่ลิงก์เอง
- อนุญาตให้ทำให้ลิงก์ใช้งานได้หากเส้นทางที่ซ้อนอยู่ทำงานอยู่
- อนุญาตให้ปิดการใช้งานลิงก์หากไม่ได้ใช้งานอยู่
รหัส:
.directive('activeLink', ['$location',
function($location) {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
var path = attrs.activeLink ? 'activeLink' : 'href';
var target = angular.isDefined(attrs.activeLinkParent) ? elem.parent() : elem;
var disabled = angular.isDefined(attrs.activeLinkDisabled) ? true : false;
var nested = angular.isDefined(attrs.activeLinkNested) ? true : false;
function inPath(needle, haystack) {
var current = (haystack == needle);
if (nested) {
current |= (haystack.indexOf(needle + '/') == 0);
}
return current;
}
function toggleClass(linkPath, locationPath) {
// remove hash prefix and trailing slashes
linkPath = linkPath ? linkPath.replace(/^#!/, '').replace(/\/+$/, '') : '';
locationPath = locationPath.replace(/\/+$/, '');
if (linkPath && inPath(linkPath, locationPath)) {
target.addClass('active');
if (disabled) {
target.removeClass('disabled');
}
} else {
target.removeClass('active');
if (disabled) {
target.addClass('disabled');
}
}
}
// watch if attribute value changes / evaluated
attrs.$observe(path, function(linkPath) {
toggleClass(linkPath, $location.path());
});
// watch if location changes
scope.$watch(
function() {
return $location.path();
},
function(newPath) {
toggleClass(attrs[path], newPath);
}
);
}
};
}
]);
การใช้งาน:
ตัวอย่างง่ายๆที่มีการแสดงออกเชิงมุมให้พูดว่า$ scope.var = 2จากนั้นลิงก์จะเปิดใช้งานหากตำแหน่งคือ/ url / 2 :
<a href="#!/url/{{var}}" active-link>
ตัวอย่าง Bootstrap parent li จะได้รับคลาสที่แอ็คทีฟ:
<li>
<a href="#!/url" active-link active-link-parent>
</li>
ตัวอย่างที่มี URL ที่ซ้อนกัน, การเชื่อมโยงจะใช้งานถ้ามี URL ที่ซ้อนกันมีการใช้งาน (เช่น/ url / 1 , / url / 2 , URL / 1/2 / ... )
<a href="#!/url" active-link active-link-nested>
ตัวอย่างที่ซับซ้อนลิงก์ชี้ไปที่หนึ่ง url ( / url1 ) แต่จะใช้งานได้หากถูกเลือกอื่น ( / url2 ):
<a href="#!/url1" active-link="#!/url2" active-link-nested>
ตัวอย่างที่มีลิงค์ปิดการใช้งานหากไม่ได้ใช้งานจะมีระดับ'ปิดใช้งาน' :
<a href="#!/url" active-link active-link-disabled>
ทั้งหมด* ใช้งาน link-คุณลักษณะที่สามารถนำมาใช้ในการรวมกันใด ๆ ดังนั้นเงื่อนไขที่ซับซ้อนมากสามารถดำเนินการ