Igor Simic
6 years ago

Angular - load external javascript dynamically

How to load external script to your Angular project, or how to reload external javascript to Angular project?  So,  for example, if you want to load external JS inside controller or based on some events.The easiest way is to use Angular plugin called oclazyload

oclazyload can be downloaded from git page and it is very easy to setup:

1 download or install oclazyload and add it to your angular app
  • var app = angular.module('MyAPP',['oc.lazyLoad']);

2 pass it to your controller and load the JS
  • app.controller('ContentCtrl',['$scope','$ocLazyLoad',function($scope,$ocLazyLoad){

myjavascript.js is loaded and executed after your URL template is loaded, so any additional HTML element are already loaded and ready to be used by javascript. Looks like loaded javascript is cached and it will not be reloaded on page switching, so if you want to reload it every time when your page(template) is  loaded you can add random number to the end of file and it will be reloaded every time:

where javascript random number is generated like this:
$rootScope.randomNumber= function(){
			return Math.floor((Math.random()*99999)+1);