1

I currently have a single page web application using Angular and UI-Router. The majority of my javascript files are being loaded on my index.html page, and those all work perfectly throughout the application.

Issue: I have a state that requires javascript code to run when the state is called. (When ui-router injects the html from this state's particular templateURL into the ui-view, I need the javascript within the injected html to run). I have been searching all day and have tried various solutions but nothing has worked.

Is there a best practice for adding this functionality? Thank you.

user2263572
  • 5,435
  • 5
  • 35
  • 57

1 Answers1

0

It's not clear, but I assume the issue is that the script tags in the HTML you're injecting aren't being run. Instead of using the standard script tag, you need to instead create a directive that allows you to do this. See Paolo's answer on this page for instructions on how to do that.

Note that you're assuming some of the responsibility for script security if you do this.

Community
  • 1
  • 1
Alvin Thompson
  • 5,388
  • 3
  • 26
  • 39
  • That looks exactly like what I'm trying to do. So would I have to create a separate directive for every javascript file that needs to be loaded into a state (not a big deal, but curious)? What is the last step, just including the element from the directive in my state's templateURL. For example, Paolo would then include within the templateUrl for the state he's loading the google api into? Thanks. – user2263572 Jun 17 '15 at 01:54
  • @user2263572: nope, once you write the directive you can re-use it anywhere. You'll need at most two: one to run javascript embedded directly in the HTML you're trying to include (for example something like, `var foo = "bar";...`) and one to load javascript from another location (like ``). Just change the `script` tags in the HTML you're trying to include to the appropriate directive and you're set. – Alvin Thompson Jun 17 '15 at 04:44
  • I was able to get lazy loading working for both types of scripts. Unfortunately, although the lazyloading works with my test scripts, it didn't work with the google charts API that I was trying to lazyload. If you think you have any idea why the new question can be found here. [link](http://stackoverflow.com/questions/30894544/angular-ui-router-lazyloading-google-charts) Thanks again for the help, i made some solid progress. – user2263572 Jun 17 '15 at 14:32