目次を生成するための AngularJS ディレクティブ
-
21-12-2019 - |
質問
見出し (h1 ~ h6) を含む HTML テキストを想像してください。私の状況では、HTML ページに DOM としても存在します。したがって、jQueryを使用すると、次のようなことをします $('.text').find('h1,h2,h3,h4,h5,h6')
すべての見出しを抽出します。
ただし、jQuery やその他の重いフレームワークは使いたくありません。angularJS でこれを行うにはどうすればよいですか?目次として表示するには、見出しを正しい順序で配置する必要があることに注意してください。
解決
だからここで私の最終的な解決策です。NGモデル部分は、テキストが更新されたときにヘッドラインを更新するために使用されます。
.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>
. 他のヒント
運が良ければ使えるはずです 角度要素 jQuery を使用する場合とほぼ同じ方法です。
angular.element('h1')
見つけます h1
要素。
Angular JLITEはここでのあなたのオプションですが、.find()はタグ名による検索に限られていることを忘れないでください。
これらhref="https://stackoverflow.com/questions/17283697/angularjs-how-to-find-using-jqlite"> so それが役立つ場合は答えます。
を使用して、クラス ".text"を持つ要素を見つけることができます。
angular.element(document.querySelectorAll(".text"));
. 所属していません StackOverflow