krzyhub krzyhub - 1 year ago 70
AngularJS Question

Angular ES6 - how to organize controllers?

I have a piece of code:

'use strict';
/*jshint esnext: true */
/*global angular: false */

import ModalCtrl from './controllers/ModalCtrl';
import ShowVersionCtrl from './controllers/ShowVersionCtrl';
import TodoListCtrl from './controllers/TodoListCtrl';

var app = angular.module('Todo', ['ngRoute'])
.controller('ModalCtrl', ModalCtrl)
.config(($routeProvider) => {
.when('/', {
templateUrl : './templates/main.html',
controller: 'ShowVersionCtrl'
.when('/list', {
templateUrl : './templates/list.html',
controller: 'TodoListCtrl'
.when('/add', {
templateUrl : './templates/add.html',
controller: 'TodoListCtrl'
.when('/search', {
templateUrl : './templates/search.html',
controller: 'TodoListCtrl'

And I have several questions:

1. Is it contrary to good practices if I assign controller before
, like
.controller('ModalCtrl', ModalCtrl)

2. Is it possible to assign multiple controllers inside
, like
controller: ['ShowVersionCtrl', 'ModalCtrl']

3. What is the best way to set global controller? And is it possible to set several of them?

4. Do I need to add
to injected template after I specified controller in

Answer Source
  1. I would say it is better to separate config and controllers in different files. And your app is small and you don't want to do that - I recommend to initiate controllers after config because in AngularJS lifecycle config is always initialize before all controllers. So it will be more naturally to look at such order.
  2. Here is answer to this problem. But answer is - no, you can not, try solution in link.
  3. As far as I got this question you want something global to wrap all your other components. I think it is better to divide your application to logical components and include them in the partial hierarchically. So you will understand how data flows in your app and which components responsible for each of app parts.
  4. You don't need ng-controller, but you need to put <ng-view> directive to let know angular where do you expect to see controller related partial with it's controller.