Using `bindToController` & `controllerAs` Together In The Same Angular 1.4+ Directive

When I looked for articles about how to use bindToController in directives, I saw a lot of code samples that look like:

What Doesn’t Work?

With that, I should be able to use the directive in the following way:
(not using a directive template here, maybe that’s what others tested!)

And that should display success, right? It doesn`t!

Things I tried:

  • Defining the controller separately via angular.controller(...), vs making it a function in the directive definition object (DDO) as above

  • In the scope, changing the property name to be different from the directive name.

What Works? The solution

Simply, swap the values of bindToController and scope!

Like this:

I already read that in Angular 1.4 you can use the bindToController property similar to how you use the scope property, meaning you use it to define what properties are created in the new scope.

I still thought I need scope: {} though to make that new scope magic work. But it turned out that this was actually ruining it. All I needed was to set it to true to have a separate scope.

Complete Sample

I have kept it stupid simple so that the main point is not lost.

See the Pen bindToController Sample by Meligy, Mohamed (@Meligy) on CodePen.

Share With Friends:

P.S. Please help me out by checking this offer, then look below for a small Thank You.

How did I learn that?

As a bonus for coming here, I'm giving away a free newsletter for web developers that you can sign up for from here.
It's not an anything-and-everything link list. It's thoughtfully collected picks of articles and tools, that focus on Angular 2, ASP.NET 5, and other fullstack developer goodies.