在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);
}
}
Run Code Online (Sandbox Code Playgroud)
注意如何select添加方法$scope,但是addPane添加了方法this.如果我将其更改为$scope.addPane,则代码会中断.
文档说实际上存在差异,但没有提到差异是什么:
以前版本的Angular(pre 1.0 RC)允许您
this与该$scope方法互换使用,但现在不再是这种情况了.内的方法上的范围限定this并且$scope是可互换的(角套this到$scope),但是不另外你的控制器构造内部.
如何this和$scope在AngularJS控制器的工作?
有两种模式用于访问控制器功能: this和$scope.
我应该在何时使用?我理解this是设置为控制器,并且$scope是视图范围链中的对象.但是使用新的"Controller as Var"语法,您可以轻松使用它们.所以我要问的是什么是最好的,未来的方向是什么?
例:
运用 this
function UserCtrl() {
this.bye = function() { alert('....'); };
}
Run Code Online (Sandbox Code Playgroud)
<body ng-controller='UserCtrl as uCtrl'>
<button ng-click='uCtrl.bye()'>bye</button>
Run Code Online (Sandbox Code Playgroud)运用 $scope
function UserCtrl($scope) {
$scope.bye = function () { alert('....'); };
}
Run Code Online (Sandbox Code Playgroud)
<body ng-controller='UserCtrl'>
<button ng-click='bye()'>bye</button>
Run Code Online (Sandbox Code Playgroud)我个人发现,this.name与其他Javascript OO模式相比,它更容易上手,更自然.
建议好吗?
在示例$ctrl中用于视图
<b>Heroes</b><br>
<hero-detail ng-repeat="hero in $ctrl.list"
hero="hero"
on-delete="$ctrl.deleteHero(hero)"
on-update="$ctrl.updateHero(hero, prop, value)">
</hero-detail>
Run Code Online (Sandbox Code Playgroud)
何时使用$ctrl以及何时$scope用于与视图交互?