I came across this question while grappling with understanding the intricacies of Angular and intricate aspects of JavaScript. I have tried to structure my inquiry in a way that simplifies it.
The conventional method of exposing variables from a controller is by defining them on
$scope
..controller('MyCtrl', function($scope) { $scope.value = 5; });
In a template, you can reference it like this, assuming that
MyCtrl
is the controller:{{value}}
When using the controllerAs syntax, such as with
ui-router
as shown below:state('mystate', { templateUrl: 'partials/some.html', controller: 'MyCtrl as ctrl' }
You can still access
value
with{{value}}
, which works fine. However, if another value is declared like this:.controller('MyCtrl', function($scope) { $scope.value = 5; this.otherValue = 10; });
With the syntax
controller: 'MyCtrl'
, referencing{{otherValue}}
does not work. However, withcontroller: 'MyCtrl as ctrl'
, you can reference them as follows:{{value}} {{ctrl.otherValue}}
Summary of point 1: You can always reference
value
with{{value}}
, but you can only referenceotherValue
when the controller is named, thus{{ctrl.otherValue}}
.My second point concerns functions and is related to point 1. Suppose two functions are defined:
.controller('MyCtrl', function($scope) { $scope.myFunc = function() {}; this.otherFunc = function () {}; });
If, once again, the
controller: 'MyCtrl'
syntax is used,myFunc
can be called from the template:<button ng-click="myFunc()">
But trying to call
otherFunc
will result in failure:<button ng-click="otherFunc()">
Now, with the
controller: 'MyCtrl as ctrl'
syntax, callingmyFunc
in these ways will fail:<button ng-click="ctrl.myFunc()"> <button ng-click="myFunc()">
However,
otherFunc
can be called by referencing the controller with its name:<button ng-click="ctrl.otherFunc()">
Summary of point 2: Only
$scope.
functions can be called conventionally without the use of the controllerAs syntax, whilethis.
functions require referencing the named controller. This differs from point 1, where$scope.
variables can be referenced regardless of controller naming.
I understand that controller constructor functions are meant for configuring the $scope
, and templates should interact with the $scope
. What distinguishes named controllers then?
I assume that the controllerAs syntax associates that custom name with the controller function itself rather than the scope, but I would appreciate clarification on this matter.
I believe these behaviors extend beyond just ui-router and are generally applicable. Therefore, I am curious about the following:
- What should be assigned to
$scope
and what shouldn't? - What should be defined within the function itself (?) and what shouldn't?
- Is there a way to access
$scope.
functions when using named controllers? - Any advice or any obvious points I might be overlooking?
Thank you in advance for your time.