Search code examples
javascriptangularjsangularjs-scopeangularjs-ng-repeatangularjs-controlleras

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


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?


Solution

  • 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/