'this' vs $scope in AngularJS controllers

后端 未结 7 1491
逝去的感伤
逝去的感伤 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:40

    I just read a pretty interesting explanation on the difference between the two, and a growing preference to attach models to the controller and alias the controller to bind models to the view. http://toddmotto.com/digging-into-angulars-controller-as-syntax/ is the article.

    NOTE: The original link still exists, but changes in formatting have made it hard to read. It's easier to view in the original.

    He doesn't mention it but when defining directives, if you need to share something between multiple directives and don't want a service (there are legitimate cases where services are a hassle) then attach the data to the parent directive's controller.

    The $scope service provides plenty of useful things, $watch being the most obvious, but if all you need to bind data to the view, using the plain controller and 'controller as' in the template is fine and arguably preferable.

提交回复
热议问题