Code, Angular, iOS and more by Aviv Ben-Yosef

Naming Your Controller-As Consistently

| Comments

Conventions have always been a problematic part of Angular, especially when they seem to change all the time.

A very common issue that I’ve been asked about again and again is what name to use in controller-as.

Here are my 2 cents on a style that, to me, makes the most sense.

First, understand that the options basically divide to either using the same name in all your components/directives, or to use a specific name in each.

I strongly recommend to use the same name in all templates. It means less typing, less thinking about boring details and of course means easier refactoring down the road.

Now, the question is what name should you use. Prior to Angular 1.5, the community seems to have settled on “vm” as the name (e.g. that’s the default in John Papa’s style guide).

But, with the introduction of components in 1.5 the default there is now “$ctrl”. Even though I personally dislike the look of $ctrl I have to recommend sticking to it. It is only a matter of time before this becomes the de-facto standard as the community upgrades to 1.5.

What about referencing parent controllers??

One of the arguments I’ve heard quite a bit for using a different name in each directive/component is so it will be possible to reference parent controllers in the scope.

But, you should never do that. Your scopes should virtually always be isolated, so that name clashing would be impossible.

And in the (truly) rare occasion where you do reference some parent controller you should do it using the require mechanism.

“Maintaining AngularJS feels like Cobol 🤷…”

You want to do AngularJS the right way.
Yet every blog post you see makes it look like your codebase is obsolete. Components? Lifecycle hooks? Controllers are dead?

It would be great to work on a modern codebase again, but who has weeks for a rewrite?
Well, you can get your app back in shape, without pushing back all your deadlines! Imagine, upgrading smoothly along your regular tasks, no longer deep in legacy.

Subscribe and get my free email course with steps for upgrading your AngularJS app to the latest 1.6 safely and without a rewrite.

Get the modernization email course!