Angularjs: how to work with controllers separated by files

3

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

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

Sample 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 index page from the site, only App.js is loaded. These files are requested when I change pages using the Angular routes.

PS: My goal is to create a website that the user does not need to load the header whenever he changes pages, only get the requested content per page. Examples are: Disqus, Google Play Store, Facebook, YouTube, and others.

    
asked by anonymous 24.10.2016 / 00:55

1 answer

2

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

Use the lazyload does not solve so he will take care of loading all his dependencies of the route before rendering his 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);
  }

}());
    
25.10.2016 / 03:55