Luis Revilla Luis Revilla - 2 months ago 5x
AngularJS Question

$scope not injected, still referenced. Why does it work?

In the Angular Material Starter App, a 'UserController' is defined without injecting the $scope service.

So in the constructor function, variables are created as properties of the This object:

function UserController( userService, $mdSidenav, $mdBottomSheet, $timeout, $log )
var self = this;

self.selected = null;
self.users = [ ];
self.selectUser = selectUser;
self.toggleList = toggleUsersList;
self.makeContact = makeContact;

But then, in the self.selectUser function, the value of the array self.users is referenced as $scope.users

function selectUser ( user ) {
self.selected = angular.isNumber(user) ? $scope.users[user] : user;

It works even though $scope was never injected. And if I change it to self.users, works as well.

Is $scope implicitly injected in every Angular controller? Does it automatically mirror the this object in a controller constructor function?

What's going on?

Here's the code


I just cloned the repo and tested it's not working as you were saying .$scope is not defined error. You have to Inject to constructor to work it No it is not automatically injected you need to pass $scope as argument to controller to use it otherwise you should get error $scope is undefined it can be like your giving conditions in selectedUser function and it never come to $scope in order to react on that.

    function UserController( userService, $mdSidenav, $mdBottomSheet, $timeout, $log , $scope) 
function selectUser ( user ) {
      //try to change this line and run code and select a user you will get error
      self.selected = angular.isNumber(1) ? $scope.users[user] : user;
      console.log($scope) //$scope is undefine