简体   繁体   English

如何在Angular中有条件地包含脚本元素

[英]How to conditionally include script element in Angular

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. 但是似乎在ng-if指令之前执行了聊天脚本。

How can I make my Angular app to check the condition first and then execute the script from <script> tag? 如何使Angular应用程序首先检查条件,然后从<script>标签执行脚本?

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. 注意,由于Angular的jqLit​​e实现如何处理<script>元素,上述方法仅在jQuery加载(Angular之前)时才有效。

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). 更干净的方法是与上述<script>相同的指令,但具有防止其多次执行的保护措施(请注意,将<script>放入指令的模板中,对jQuery的要求与上述解决方案相同)。

Inline Javascript will always have priority over Angular (parsed first by the browser). 内联Javascript始终比Angular优先(由浏览器首先解析)。 The best way is to inject/execute the javascript inside your controller with a condition or creating a directive. 最好的方法是使用条件或创建指令在控制器内部注入/执行javascript。

一种原生且轻量级的方法,即没有jQuery,没有Angular指令,将使用类似于https://github.com/anywhereway/scriptswitch的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM