在AngularJS主页的“创建组件”部分中,有这样一个例子:
controller: function($scope, $element) {var panes = $scope.panes = [];$scope.select = function(pane) {angular.forEach(panes, function(pane) {pane.selected = false;});pane.selected = true;}this.addPane = function(pane) {if (panes.length == 0) $scope.select(pane);panes.push(pane);}}
请注意select方法是如何添加到$scope的,但addPane方法是如何添加到this的。如果我将其更改为$scope.addPane,代码就会中断。
留档说事实上是有区别的,但没有提到区别是什么:
以前版本的Angular(1.0 RC之前)允许您将
this与$scope方法互换使用,但情况不再如此。在作用域this和$scope上定义的方法内部是可互换的(角度集this到$scope),但在控制器构造函数内部不能。
this和$scope如何在AngularJS控制器中工作?