I found this in AngularJS style guide
Prefer using controller as syntax and capture this using a variable:
That means that I can assign all my functions and the model to the controller via this and access via the alias in the view. If I do so, I find that I really have no use for the $scope
anymore. One exceptions is when I want to access something that's in the $rootScope
.
So, having the quoted suggestion in mind, when should I use $scope
at all if I'm not interested in accessing anything in the $rootScope
?
That is, should I move everything to controller's this
? If not, then what should stay in the $scope
?
when should I use $scope at all if I'm not interested in accessing anything in the $rootScope?
$scope
is not just for accessing to properties or functions in the $rootScope
. Example (not too often, by the way): Suppose you need to update a DOM element not in the angular way, it means updating it through any external library which modifies the component value (visually), but the ng-model
of the component doesn't get updated and you need it to! What to do? Simple: $scope.$digest
(depending on what you do, there might be any other angular function required).should I move everything to controller's this?
angular
.module('myapp', [])
.controller('foo', function() {
var vm = this;
// only this will be available in the view thanks to the controller as syntax
vm.wizard = {
userID: null,
totalCartCount: 0
}
// stuff used only inside the controller
vm.private = {
subtotalByProducts: [],
readyToCheckoout
}
// only "public" stuff is returned here
return vm.wizard;
// functions
});
If not, then what should stay in the $scope?
What you put in your $scope
is completely up to you, as it is using the controller as
syntax, but keep in mind that everything in the $scope
is accessible in the view. The idea is to reduce the amount of variables passed to the view. This could not be noticeable in small webapp, but when the size of the app gets greater you can notice some changes (more time loading, etc).
This is a matter of perspective of each developer and how fond could be any of us of using best practices.
$scope
should be used for the things that cannot be done with this
(which equals to controller instance and becomes a property on $scope
when being used with controllerAs syntax). This includes all scope methods.
For some of these methods $scope
can generally be replaced with $rootScope
, but it is semantically correct to not do that (not doing that may also be good for testability). The examples are $apply
/$evalAsync
without string argument, $on
/$broadcast
/$emit
for events which are used exclusively on root scope.
For some of these methods $scope
cannot be replaced with $rootScope
, doing that will result in unexpected behaviour.
When $scope
is being used for scope properties, it can be replaced with this
and controllerAs syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With