想象一个包含标题 (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>

其他提示

你很幸运,应该能够使用 角元 几乎与使用 jQuery 的方式完全相同。

angular.element('h1') 会发现 h1 元素。

Angular jqLit​​e 是您的选择,但不要忘记 .find() 仅限于按标签名称查找。

检查这些 所以 所以 如果有帮助的话请回答。

您可以使用以下命令找到具有“.text”类的元素

angular.element(document.querySelectorAll(".text"));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top