What is the difference between "this" and "$ scope"?

8

No AngularJS we use $scope to share information between domains of a controller . There is also the Controller as syntax that allows us to use this for the same purpose.

  • With $scope :

    function MeuController($scope) {
      $scope.mensagem;
    }
    
    <div ng-controller='MeuController'>
      {{mensagem}}
    </div>
    
  • With this :

    function MeuController() {
      this.mensagem;
    }
    
    <div ng-controller='MeuController as vm'>
      {{vm.mensagem}}
    </div>
    
  • What is the difference between the two approaches and when should I use each?

        
    asked by anonymous 02.06.2017 / 14:28

    2 answers

    7

    Basically, both the use of $scope and this in angle are intended to share information between view and controller .

    The difference is that when using this , you must use an alias for the controller in your view .

    For example:

    <div ng-controller="MeuController as meu"></div>
    

    The great advantage I see when using this is that if you have multiple controllers within the other, and at some point need to name variables with the same name, this alias will act as a namespace that will separate the values.

    Note : When using this without as in the view (alias definition), you can access the information through the $ctrl variable (at least this is how it works in component definition ).

    In the case of $scope , you can define your variables, being able to access them immediately, without needing a "prefix" as in the case above.

    Note that in some cases, you will need $scope , even using this . For example, in case of setting a watcher manually.

    controller('MeuController', function ($scope) {
    
        var vm = this;
    
        vm.name = 'Wallace';
    
    
        $scope.$watcher('vm.name', function () {
    
            vm.first_name = name.split(' ')[0];
        })
    })
    

    Not to mention that, among other information, $scope contains special information such as $parent , which references the parent controller of the current controller.

        
    02.06.2017 / 14:55
    0

    "$ scope" is a special angular variable that has the controller context data.

    "this" is a reserved javascript word, which always points to the object where the method is running, if the method is in the angle controller, it is referencing the controller.

        
    02.06.2017 / 14:41