javascript – Angularjs: working with file-separated controllers


I use a service to make each route make 3 http.get requests: one for the content that the server will generate in a part of the page, for a js file that contains your controller and for a css file.

My problem occurs when I load this script that contains the controller, and nothing happens on my requested page.

Example of my code:


angular.module('main', [myModulesHere...])

.config(function($routeProvider, $locationProvider) {


    .when('/about', {
        template: '',
        controller: 'aboutLoad'

.controller('aboutLoad', function($scope, myCustomHttpService) {

    // Aqui o método getRoute vai tratar-se de fazer a
    // requisição http.get, e enviar o conteúdo do servidor
    // para o ng-view quando tudo for completado

    myCustomHttpService.getRoute('/about', {
        js: './public/view/main/js/AboutController.js',
        css: './public/view/main/css/about.css'


angular.module('main').controller('AboutController', function($scope) {
    $scope.myText = 'Página: Sobre Nós';


<div ng-controller="AboutController">
    <h2 ng-bind="myText"></h2>

When I load the site's index page, only App.js is loaded. These files are requested when I switch pages using Angular's routes.

PS: My goal is to create a site that the user doesn't need to load the header every time he changes pages, just get the requested content per page. Examples are: Disqus, Google Play Store, Facebook, YouTube, and others.


Renan uses ocLazyLoad to load your files on demand (Calling only when you need to use those files).

Use lazyload in the solve so it will take care of loading all your route dependencies before rendering your view.

(function() {
  'use strict';

  var app = angular.module('myApp', ['ui.router', 'oc.lazyLoad']);

  function routes($stateProvider) {
    var about = {
      name: 'about',
      url: '/about',
      controller: 'AboutController',
      controllerAs: 'aboutCtrl',
      templateUrl: 'about.html',
      resolve: {
        lazyLoad: function($ocLazyLoad) {
            return $ocLazyLoad.load({
              files: ['aboutController.js', 'about.css']


Scroll to Top