Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have a js file in my partial view. How would I load it dynamically when that partial is loaded?

My directory structure is

app

---css

------style.css

----js

-------app.js

-------appRotes.js

-------script.js

----views

-------home.html

-------about.html

----index.html

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>

<body ng-app="myapp">

<p><a href="#/">Main</a></p>

<a href="#about">Red</a>

<div ng-view></div>

<script src="js/app.js"></script>
<script src="js/appRoutes.js"></script>
</body>
</html>

My app.js

angular.module("myapp", ["myapp.routes"]);

My appRoutes.js

angular.module("myapp.routes",["ngRoute"]).
config(function($routeProvider, $locationProvider){
    $routeProvider.
        when("/",{
            templateUrl : "views/home.html"
        })
        .otherwise({
        redirectTo: '/'
    })
    .when("/b",{
            templateUrl : "views/about.html"
        })
        .otherwise({
        redirectTo: '/'
    });


});

My about.html

<h1>About</h1>
<script src="script.js"></script>
share|improve this question
up vote 0 down vote accepted

can use oclazyload for dynamic js file loading using ngRoute

$routeProvider  

      .when('/time',
            {
                controller: 'timeController', 
                templateUrl: 'views/home.html', 
                resolve: {
                    lazy: ['$ocLazyLoad', function($ocLazyLoad) {
                        return $ocLazyLoad.load([{
                            name: 'myApp',
                            files: ['js/AppCtrl.js']
                        }]);
                    }]
                }
            })

using ui router

$stateProvider.state('index', {
  url: "/", // root route
  views: {
    "lazyLoadView": {
      controller: 'AppCtrl', // This view will use AppCtrl loaded below in the resolve
      templateUrl: 'views/home.html'
    }
  },
  resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
    loadMyCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
      // you can lazy load files for an existing module
             return $ocLazyLoad.load('js/AppCtrl.js');
    }]
  }
});

you can install it using bower

bower install oclazyload --save

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.