How to conditionally include script element in Angular

本秂侑毒 提交于 2019-12-10 09:28:02

问题


I'm trying to conditionally include a chat on my page:

<body ng-app="myApp">
  <!-- some code -->

  <script type="text/javascript" ng-if="expression">
    window.$zopim||(function(d,s){var z=$zopim=function(c){z._.push(c)},$=z.s=
    d.createElement(s),e=d.getElementsByTagName(s)[0];z.set=function(o){z.set.
    _.push(o)};z._=[];z.set._=[];$.async=!0;$.setAttribute("charset","utf-8");
    $.src="//v2.zopim.com/?my-zopim-id";z.t=+new Date;$.
    type="text/javascript";e.parentNode.insertBefore($,e)})(document,"script");
  </script>
</body>

but it seems that the chat script gets executed before ng-if directive.

How can I make my Angular app to check the condition first and then execute the script from <script> tag?


回答1:


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.




回答2:


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).




回答3:


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



来源:https://stackoverflow.com/questions/39392578/how-to-conditionally-include-script-element-in-angular

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