I decided to put this question up because I got to a point where I'm pretty confused about how Angular and the more delicate parts of JavaScript work. I try to formulate my question so it can be broken down.
The standard way of exposing variables from a controller is to declare them on
$scope
..controller('MyCtrl', function($scope) { $scope.value = 5; });
Then from a template reference it like this, assuming
MyCtrl
is the controller:{{value}}
When I use the controllerAs syntax, for example with
ui-router
like this:state('mystate', { templateUrl: 'partials/some.html', controller: 'MyCtrl as ctrl' }
I can still get
value
with{{value}}
so this works. However if I declare another value like this:.controller('MyCtrl', function($scope) { $scope.value = 5; this.otherValue = 10; });
Then with
controller: 'MyCtrl'
syntax, I can not reference{{otherValue}}
. However with thecontroller: 'MyCtrl as ctrl'
syntax, I can reference them like this:{{value}} {{ctrl.otherValue}}
Summary of point 1: I can always reference
value
like{{value}}
but can only referenceotherValue
if the controller is named, so{{ctrl.otherValue}}
.My second point is about functions and the topic is similar to point 1. Suppose I define two functions:
.controller('MyCtrl', function($scope) { $scope.myFunc = function() {}; this.otherFunc = function () {}; });
Now if again as above I use the
controller: 'MyCtrl'
syntax, from the template I can callmyFunc
:<button ng-click="myFunc()">
But this will not work:
<button ng-click="otherFunc()">
Now with
controller: 'MyCtrl as ctrl'
syntax, callingmyFunc
like these will not work:<button ng-click="ctrl.myFunc()"> <button ng-click="myFunc()">
But I can call
otherFunc
by referencing the controller with the name:<button ng-click="ctrl.otherFunc()">
Summary of point 2: I can only call
$scope.
functions like I'm used to when I don't use the controllerAs syntax, and can only callthis.
functions when I reference the named controller. This is in contrast with point 1 where I can reference the$scope.
variable from either named or unnamed controller definition.
I know controller constructor functions are for setting up the $scope
, and templates should use the $scope
, but what is different about named controllers then?
I'm guessing the controllerAs syntax causes that custom name to point to not the scope but the controller function itself, but I would be grateful if somebody would clear this up for me.
I also think these behaviours are not related to just ui-router but it's generally how it works, so I would also like to know:
- What should be set on
$scope
and what shouldn't? - What should be set on the function itself(?) and what shouldn't?
- Is there a way to access
$scope.
functions when using named controllers? - Any advice or some obvious point I'm missing?
Thank you for your time in advance.