Is there really no difference between AngularJS $scope and Controller as syntax?

111 views Asked by At

I am learning angularJS and while learning found the controller as syntax much easier to read and a little easier for me coming from the OO world to understand. I have read several articles and SO answers that all seem to point to $scope and the 'controller as ' syntax being the same and that the 'controller as' syntax is just syntactical sugar.

However, I posted another question on SO here and the user that answered the question says that I have to still inject $scope to use the 'ui select' directives even though I am using the controller as syntax. Which is it? And if I don't have to use the $scope, what am I missing to get the 'controller as' syntax to work with ui-select?

3

There are 3 answers

0
Shaun Scovil On BEST ANSWER

The controllerAs syntax exposes your controller to the template, so rather than binding a bunch of properties to $scope in your controller, you can make them properties of an instance of your controller. (Controllers are JavaScript "class" constructors.)

So if you have the following:

angular.module('myApp')
  .controlller('MyController', function() {
    var vm = this;
    vm.foo = 'bar';
  });

...you can access it in your template like this:

<div ng-controller="MyController as vm">
  {{ vm.foo }}
</div>

Now, if you want to access scope variables in your controller -- or call a scope method such as $on -- you still need to inject $scope into your controller. Note the $ before scope, which indicates it is a service. This $scope service simply exposes the current scope.

All of that said, if you find yourself injecting $scope into your controller, you should question your approach. Better to create a custom directive and access scope via the link function, or access scope from the template.

Recommended reading: http://www.johnpapa.net/do-you-like-your-angular-controllers-with-or-without-sugar/

0
Michael Warner On

Sorry this is long with no examples.

A controller in both forms Controller and Controller As are functions. The main difference from my understanding is Controller As when called is called using the new keyword which is why the 'this' syntax works. This is also why you can do the prototype inheritance with Controller As syntax while you can't do that with the normal Controller syntax. The other cool part about Controller As is the namespacing you can place the scope variables in which means in the HTML it is easy to reason which parts go to which controller. If you want I can give examples but that is the core difference from my understanding.

0
Scott Schwalbe On

controller as is nice because you can nest ng-controllers and know which controller you're acting on

<div ng-controller="Ctrl1 as c1">
  <--Using c1 here -->
  <div ng-controller="Ctrl2 as c2">
  <-- Using c2 here -->
  </div>
  <--Using c1 here -->
</div>