'this' vs $scope in AngularJS controllers

后端 未结 7 1492
逝去的感伤
逝去的感伤 2020-11-21 05:18

In the \"Create Components\" section of AngularJS\'s homepage, there is this example:

controller: function($scope, $element) {
  var panes = $scope.panes = [         


        
7条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 05:38

    Previous versions of Angular (pre 1.0 RC) allowed you to use this interchangeably with the $scope method, but this is no longer the case. Inside of methods defined on the scope this and $scope are interchangeable (angular sets this to $scope), but not otherwise inside your controller constructor.

    To bring back this behaviour (does anyone know why was it changed?) you can add:

    return angular.extend($scope, this);
    

    at the end of your controller function (provided that $scope was injected to this controller function).

    This has a nice effect of having access to parent scope via controller object that you can get in child with require: '^myParentDirective'

提交回复
热议问题