0

What is the best way to write a controller in AngularJS? I've seen it written many different ways and it's confusing on which way is better then the rest.

Personally I write it like this,

var app = angular.module('app'); // app is created elsewhere, just referencing it

var MainController = function($scope) {
    // Do Stuff
}

app.controller("MainController", [MainController]);

I think writing it this way is the cleanest way to write it. Everything is separated so it's easier to read.

The most common way I've seen it written is like this,

app.controller("EventController", function EventController($scope) {
    // Do stuff
}

I would like to know, if there any pitfalls in the future that would happen if I keep writing them the way I prefer? Why is one way better than the other?

Graham
  • 7,431
  • 18
  • 59
  • 84
Jimenemex
  • 3,104
  • 3
  • 24
  • 56
  • 2
    Please see this guide: https://github.com/johnpapa/angular-styleguide/tree/master/a1#controllers – Zooly Aug 17 '17 at 14:17

1 Answers1

3

The difference between the two, (besides what you are already used to) is that the first is a function that is declared once, and the second is an inline-function.

For your reference, here are a few SO Posts about the actual differences, and when to use each of them.

Also since you are asking specifically about AngularJS, you should check out the following two styling guides.

Rabbi Shuki Gur
  • 1,656
  • 19
  • 36