What is the simplest way to load a controller when i change the view?

178 Views Asked by At

I'd like to load a controller when I change from one view to another.

For example, I'm in the home page and user wants to go to the log in page. I have a LoginController in a file that is not include in app.js(main AngularJS script) that I want to load only if the user goes to Login page.

I saw differents solutions but are very complicated, my controllers are very simple and I only want to have them in different files but I don't want to load a controller if I are not going to use them.

Thanks.

3

There are 3 best solutions below

2
On

A Single-Page-Application, which AngularJS is a framework for, loads all its views and code beforehand. This is to provide a fast and fluent application on the cost of a (bit) bigger loading time. Since the code is not meant to be loaded dynamically by AngularJS you will not find a clean solution to do so out there. Furthermore i do not see any reasons to do so in the first place. As long as your application is not one of the biggest applications out there it simply doesn't make any sense to load your controllers dynamically. If you put all your code together in one file and minimize it, which you should do in production anyhow, loading your controllers will be the least of your problems. It is faster to put everything in one file and fetch it with one request than load it dynamically between the views, which is why the SPA architecture gets used more and more often nowadays.

My advice: don't do it, don't try it. It's as it is for reasons and it's good as it is :)

However, if you really really want to achieve this your only way to do so is by doing everything on your own: Script loading, Controller instantiation, etc.

1
On

You probably need ng-route. This is a module that does exactly what you want to. (along with other functionality -> ngRoute. you define routes in the next way.

var app = angular.module('app ', []);
app .config(['$routeProvider',
  function($routeProvider) {
  $routeProvider.
    when('/login', {
      templateUrl: 'login.html',
      controller: 'loginController'
    }).
    when('/home', {
      templateUrl: 'home.html',
      controller: 'homeController'
    }).
  otherwise({
    redirectTo: '/home'
  });
}]);

Also, you have to declare the loginController, but don't worry, a controller gets destroyed if you change the view it was bound to, and recreated when you open your loginpage again.

0
On

I believe what you are looking for is https://oclazyload.readme.io/. It will dynamically load modules. I believe it is build upon require.js.