7

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?

5
  • 3
    You can't do it with ng-if you will have to put an if statement in the actual javascript. Commented Sep 8, 2016 at 13:44
  • @BobBrinks You can. Commented Sep 8, 2016 at 14:20
  • @estus Ah yes i see. You probably shouldn't. Commented Sep 8, 2016 at 14:23
  • 1
    @BobBrinks That's true! Commented Sep 8, 2016 at 14:23
  • How about a very simple <div ng-if="condition" ng-include="file/with/javascript/code.html"></div> Commented Oct 20, 2017 at 18:02

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

interesting way
2

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.

1 Comment

could you explain the solution in more detail?
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.