1

I am looking at some samples of how controllers work in angular and I see two ways of declaring them, one with just controller name and one with "as somename". Examples that use ng-controller = "myController" take a $scope as dependency when defining controller. Then model is then set on the $scope, something like this

 $scope.mymodel = somevalue;

Example that uses "as" syntax such as ng-controller = "MyControler as vm" never uses $scope when setting up the model but ratther assigns it to "this" and binds using {{vm.something}}.

in controller:

var vm =this;

vm.something = somevalue;

How is that working in second example? Is that new way in latest version?

epitka
  • 17,275
  • 20
  • 88
  • 141
  • 1
    `as` is different than using `this` in controller. Recent changes allowed using `this` instead of `$scope` in controller. `as` is used in markup – charlietfl Nov 14 '13 at 22:44
  • 1
    Here's a nice 5 minute video that lines up nicely with your question: http://egghead.io/lessons/angularjs-experimental-controller-as-syntax – KayakDave Nov 14 '13 at 22:54

1 Answers1

0

Using the "as" syntax exposes your entire controller to your view. In my opinion, that is a bad practice. Although I'm not sure which one is better performance wise, but using 'this' in javascript already has plenty of issues of its own, and I don't recommend adding another meaning to 'this'. So I would stick to $scope (since that is what they're using in the docs as well). See this topic if you want to know more context about how the 'as' syntax work: 'this' vs $scope in AngularJS controllers

Community
  • 1
  • 1
trekforever
  • 3,914
  • 25
  • 29