AngularJS 指令生成目录
-
21-12-2019 - |
题
想象一个包含标题 (h1-h6) 的 html 文本。在我的情况下,它也以 DOM 形式出现在 html 页面中。所以使用 jQuery 我会做类似的事情 $('.text').find('h1,h2,h3,h4,h5,h6')
提取所有标题。
但我不想使用 jQuery 或任何其他重型框架。我怎样才能用 angularJS 做到这一点?请记住,我需要以正确的顺序排列标题才能将其显示为目录。
解决方案
所以这是我的最终解决方案。ng-model部分用于在文本更新时更新标题。
.directive('tableOfContents', function(){
return {
restrict:'A',
require:'?ngModel',
link : function(scope, elm, attrs,ngModel) {
function updateHeadlines() {
scope.headlines=[];
angular.forEach(elm[0].querySelectorAll('h1,h2,h3,h4,h5,h6'), function(e){
scope.headlines.push({
level: e.tagName[1],
label: angular.element(e).text(),
element: e
});
});
}
// avoid memoryleaks from dom references
scope.$on('$destroy',function(){
scope.headlines=[];
});
// scroll to one of the headlines
scope.scrollTo=function(headline){
headline.element.scrollIntoView();
}
// when the html updates whe update the headlines
ngModel.$render = updateHeadlines;
updateHeadlines();
}
}
})
用法:
<a ng-repeat="headline in headlines" ng-click="scrollTo(headline)">{{headline.label}}</a>
<div table-of-contents ng-model="html">{{html}}</div>
不隶属于 StackOverflow