cansadadeserfeliz
cansadadeserfeliz

Reputation: 3133

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.

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

Upvotes: 7

Views: 6594

Answers (3)

AnyWhichWay
AnyWhichWay

Reputation: 774

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

Upvotes: 0

Estus Flask
Estus Flask

Reputation: 222369

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

Upvotes: 4

Thomas Theunen
Thomas Theunen

Reputation: 1274

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.

Upvotes: 2

Related Questions