How to use <head> tag with Angular directive

和自甴很熟 提交于 2019-12-09 06:41:16

问题


I tried this in my Angular app, but it does not work. So I tried inserting a custom tag(<mytag>) into the head and made the directive work with this by replacing "head" with "mytag".

This however is not really what I intended, because it adds <mytag> to the body instead of the <head>

Does anyone know how to make it work with the head-tag?


回答1:


I had the same challenge. Make sure that your angular app is initialized on the html tag. Then this solution works out of the box.

However for us this was not an ideal solution. So I modified Zack Boman (tennisgent) https://github.com/tennisgent/angular-route-styles code, so that it could be used anywhere after app initialization.

  • Renamed the directive to: zbRouteStyles
  • Modified the restrict to include attributes: restrict: 'EA'
  • Changed the line: elem.append($compile(html)(scope)); to angular.element('head').append($compile(html)(scope));

With these changes I was able to add the directive to any tag after my angular app was initialized even the tag that my app is initialized on.

e.g.:

<div ng-app="myApp" zb-Route-Styles> <div>



来源:https://stackoverflow.com/questions/23061958/how-to-use-head-tag-with-angular-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!