0

*Disclaimer: I am an Angular noob.

This is a more a style/standards question. I have an AngularJs SPA app where the template pages each have some javascript associated with elements on the template.

If I load the js in the index.html then it errors because the element it is binding to is not loaded yet.

If I load the js in the bottom of the template file with a <script> tag, it seems to be executed as a synchronous request because I get the "Synchronous XMLHttpRequest is deprecated" error in the console.

The solution to use $.getScript(url); was provided previously and that does seem to work.

However, many years of coding have taught me that when you have to hack something like that, you are probably violating some design rule.

Is there some design guidance about when/where/how to include javascript in an angular template when said javascript is bound to elements on that template?

Community
  • 1
  • 1
Steve Sheppard
  • 161
  • 1
  • 11
  • use directives to manage dom related scripts. A directive will only run when associated element actually exists. Otherwise look into using third part script loaders – charlietfl Sep 14 '16 at 17:41
  • So, something like [this jsfiddle](https://jsfiddle.net/1p5L00qh/6/) to attach the required behaviors to each of the elements in the js file associated with the template? – Steve Sheppard Sep 14 '16 at 18:40
  • yes...but also note that for most user events angular already has core directives built in – charlietfl Sep 14 '16 at 18:42
  • I think you filled the gaps I had. It turns out that the author of the library I was using, [Sortable](https://github.com/SortableJS), has an Angular version as well. I will switch to the Angular version and I bet the implementation will feel a lot less forced. If you will add an answer I will accept it. Thank you for the education. – Steve Sheppard Sep 14 '16 at 19:45

1 Answers1

1

For any dom related code use a directive. This assures that the element the directive is bound to exists at the time the code is run and will run for each instance of that directive

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Found this [article](http://weblogs.asp.net/dwahlin/dynamically-loading-controllers-and-views-with-angularjs-and-requirejs) by Dan Wahlin later that mirrored my feeling exactly along with his solution. – Steve Sheppard Sep 15 '16 at 14:10