Vignesh
Vignesh

Reputation: 1063

angular controller as syntax, still need $scope for special occasion?

I am using angular's 'controller as somename' syntax.

let's say the below function is my controller

function myCOntroller($scope)
{
  $scope.$emit('event');
}

the above function is working. I tried like below

function myController()
{
  var reference = this;
  reference.$emit('event');
}

this is not working. when I can use reference for data bindings. why I can't use it for this kind of things. I thought reference now have all the functions that $scope had. doesn't it makes sense if $emit works this way?

NOTE: Sorry about the code samples. I just asked this question as a proof of concept, so don't have any real code.

Upvotes: 0

Views: 242

Answers (2)

LetterEh
LetterEh

Reputation: 26706

"controllerAs" doesn't make this == $scope.

Using best-practice before controllerAs, a controller should have been used with a scope.

angular.module("myApp")
.controller("myController", ["$scope", function MyController ( $scope ) {
    var myControl = { data: 123 };
    $scope.myControl = myControl;
}]);

The HTML would then look like

<div ng-controller="myController">{{ myControl.data }}</div>

With controllerAs, this is the controller (NOT the $scope), which means that you don't have to put anything on the $scope and you can just ignore it, most of the time, unless you have a specific need (events, directives with attributes, etc).

this.$scope == $scope

angular.module("myApp")
.controller("myController", [function MyController ( ) {
    var myController = angular.extend(this, { data: 123 });
    myController.$scope.$emit( /* ... */ );
}]);

Which lets you write

<div ng-controller="myController as myControl">
    {{ myControl.data }} <!-- === $scope.myControl.data -->
   <!-- "as" sets the name of the controller, on the scope -->
   <!-- $scope.myControl.$scope === $scope -->
</div>

Upvotes: 1

Estus Flask
Estus Flask

Reputation: 222989

As already stated here,

'Controller as' is a syntactic sugar that was introduced in 1.2 and tried to fix the experience from $scope (at least the part of it that suffered from undesirable effects of scope prototypal inheritance).

<body ng-controller="MyCtrl as myCtrl">
...
app.controller('MyCtrl', function () {
  ...
});

is identical to

<body ng-controller="MyCtrl">
...
app.controller('MyCtrl', function ($scope) {
  $scope.myCtrl = this;
  ...
});

It doesn't eliminate the need for scope but introduces useful pattern into the controller (note that you don't need to inject $scope in the former example, unless you need $scope.$on, etc. there).

So use this instead of $scope when you want it to act as a model.

Upvotes: 1

Related Questions