How to conditionally include script element in Angular

泪湿孤枕 提交于 2019-12-05 17:29:26

Inline Javascript will always have priority over Angular (parsed first by the browser). The best way is to inject/execute the javascript inside your controller with a condition or creating a directive.

It can be achieved with a trick:

  <script ng-if="..." type="{{ 'text/javascript' }}">
    ...
  </script>

The binding will prevent the script from being executed in normal way.

Notice that the above will work only when jQuery was loaded (prior to Angular), due to the way how Angular's jqLite implementation treats <script> elements.

The cleaner way would be a directive that does the same as <script> above but has safeguards that would prevent it from multiple executions (notice that putting <script> into directive's template has the same requirements on jQuery as the solution above).

A native and light weight approach, i.e. no jQuery, no-Angular directives, would be to use something like https://github.com/anywhichway/scriptswitch.

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