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);
}
}
this.addPane = function(pane) { ... }
<a ng-click="addPane(newPane)">won't work</a>
<div ng-controller="ParentCtrl">
<a ng-click="logThisAndScope()">log "this" and $scope</a> - parent scope
<div ng-controller="ChildCtrl">
<a ng-click="logThisAndScope()">log "this" and $scope</a> - child scope
</div>
</div>
$scope.logThisAndScope = function() {
console.log(this, $scope)
}
之所以将'addPane' 分配给它,是因为<pane>
指令。
pane
指令确实require: '^tabs'
,它将来自父指令的 tabs 控制器对象放入链接函数。
addPane
分配给this
以便pane
链接功能可以看到它。然后在pane
链接函数中, addPane
只是tabs
控制器的属性,而只是 tabsControllerObject.addPane。因此,窗格指令的链接功能可以访问 tabs 控制器对象,因此可以访问 addPane 方法。
我希望我的解释很清楚.. 这很难解释。
我刚刚读到了关于两者之间差异的非常有趣的解释,并且越来越喜欢将模型附加到控制器,并为控制器添加别名以将模型绑定到视图。本文是http://toddmotto.com/digging-into-angulars-controller-as-syntax/ 。他没有提到它,但是在定义指令时,如果您需要在多个指令之间共享某些内容并且不想要服务(在某些情况下,服务很麻烦),则将数据附加到父指令的控制器。 $ scope 服务提供了很多有用的东西,其中 $ watch 最明显,但是如果您需要将数据绑定到视图,则可以在模板中使用普通控制器和'controller as' 很好,并且可以说是更可取的。
我建议您阅读以下文章: AngularJS:“Controller as” 还是 “$ scope”?
它很好地描述了使用 “Controller as” 来公开变量而不是 “$ scope” 的优点。
我知道您是专门询问方法而不是变量的,但是我认为最好坚持一种技术并与之保持一致。
因此,我认为,由于帖子中讨论了变量问题,因此最好只使用 “Controller as” 技术,并将其应用于方法。
<div data-ng-controller="YourController as aliasOfYourController">
Your first pane is {{aliasOfYourController.panes[0]}}
</div>
return angular.extend($scope, this);
$scope.functionName(){
this.name="Name";
//or
$scope.myname="myname"//are same}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>this $sope vs controller</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<script>
var app=angular.module("myApp",[]);
app.controller("ctrlExample",function($scope){
console.log("ctrl 'this'",this);
//this(object) of controller different then $scope
$scope.firstName="Andy";
$scope.lastName="Bot";
this.nickName="ABot";
this.controllerMethod=function(){
console.log("controllerMethod ",this);
}
$scope.show=function(){
console.log("$scope 'this",this);
//this of $scope
$scope.message="Welcome User";
}
});
</script>
</head>
<body ng-app="myApp" >
<div ng-controller="ctrlExample">
Comming From $SCOPE :{{firstName}}
<br><br>
Comming from $SCOPE:{{lastName}}
<br><br>
Should Come From Controller:{{nickName}}
<p>
Blank nickName is because nickName is attached to
'this' of controller.
</p>
<br><br>
<button ng-click="controllerMethod()">Controller Method</button>
<br><br>
<button ng-click="show()">Show</button>
<p>{{message}}</p>
</div>
</body>
</html>