Ricky
Ricky

Reputation: 2907

Angular - When to use $scope versus not

When do we use $scope, versus not use it? It seems I can get away without it, at least as far as the controller definition is concerned (See following examples).

Am I correct in this? Can you please provide an example where this/self would not work, and we are forced to use $scope?

// Method 1: Not using $scope
function LoginController() {
    var self = this;
    this.username = "";
    this.password = "";

    this.login = function() {
        if( (self.username === 'admin') && (self.password === 'admin') ) {
            // Do something
        }
    }
}

// Method 2: Using $scope
function LoginController($scope) {
    $scope.username = "";
    $scope.password = "";

    $scope.login = function() {
        if( ($scope.username === 'admin') && ($scope.password === 'admin') ) {
            // Do something
        }
    }
}

Upvotes: 1

Views: 79

Answers (3)

AKS
AKS

Reputation: 53

Possibly in the case of $emit and $broadcast we may always need $scope.

But Method 1 is very useful complex parent and child implementation to avoid confusion, yes, hacks are there to prefix the names by parent and child, but still very useful in parent and child/s implementation.

Upvotes: 0

David L
David L

Reputation: 33815

The current Angular 2.0 migration path describes a world without $scope in the near future and highly recommends that you follow the Angular style guide, which in turn recommends using controllerAs syntax wherever possible, in order to prepare for potential migration and to adhere to best practice.

That said, there are currently a few instances where you have to use $scope.

$scope.$on
$scope.$broadcast
$scope.$emit
$scope.$watch
$scope.$apply

None of these special cases apply for your example, so you should be using controllerAs instead of $scope, I.E:

ng-controller="MyController as MyCtrl"

If you must access $scope in order to use one of the methods above, you can inject it into your controller while still using controllerAs syntax:

function LoginController($scope) {
    var self = this;
    self.username = "";
    self.password = "";

    self.login = function() {
        if( (self.username === 'admin') && (self.password === 'admin') ) {
            // Do something
        }
    }

    $scope.$on('event', function () {});
}

Upvotes: 4

Mike Feltman
Mike Feltman

Reputation: 5176

Method #1 is widely considered best practice. I try to avoid direct references to $scope whenever possible.

$scope is not in Angular 2.0. By avoiding references to it your eventual migration should go easier.

John Papa's style guide is a great reference for best practices: https://github.com/johnpapa/angular-styleguide

Upvotes: 2

Related Questions