javascript – Angularjs: working with file-separated controllers

Question:

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:

app.js

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

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

    $locationProvider.html5Mode(true);

    $routeProvider
    .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'
    });
})

AboutController.js

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

AboutView.php

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

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.

Answer:

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']);
  app.config(routes);

  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']
            });
        }
      }
    };

    $stateProvider.state(about);
  }

}());
Scroll to Top