[英]AngularJS scope of controller variable depending on if it's attached to scope or this
I have following controller definition: 我有以下控制器定义:
var app = angular.module("myapp");
app.controller("ViewCtrl", function($scope) {
this.panelVisible = true;
this.panelShowHide = function() {
this.panelVisible = !this.panelVisible;
}
});
And here is my view: 这是我的看法:
<body ng-controller="ViewCtrl as view">
<a href="" ng-click="view.panelShowHide()">Button</a>
{{view.panelVisible}}
</body>
From my view I am calling panelShowHide function, and contrary to my expectation this.panelVisible = !this.panelVisible
line somehow updates controller variable (defined in this.panelVisible = true;
line) 从我的角度来看,我正在调用panelShowHide函数,与我的预期相反,
this.panelVisible = !this.panelVisible
行以某种方式更新了控制器变量(在this.panelVisible = true;
行中定义)
How is that possible? 那怎么可能? I understand if I did
$scope.panelVisible
, but since I am doing this.panelVisible
in panelShowHide function, shouldn't that line create and update new variable defined within the scope of function? 我知道我是否执行了
$scope.panelVisible
,但是由于我正在panelShowHide函数中执行this.panelVisible
,因此该行是否不应该在函数范围内创建和更新定义的新变量?
I am asking this so that I better understand the scope in AngularJS since in some more complicated cases (like using $http.get) my this.reference is "properly resolved" (to local variable) and I would prefer the be able to reference controller variables (encapsulate logic). 我问这个问题是为了更好地理解AngularJS的范围,因为在一些更复杂的情况下(例如使用$ http.get),我的this.reference是“正确解析的”(局部变量),我希望能够引用控制器变量(封装逻辑)。
What the ng-controller="ViewCtrl as view"
feature does is publish an instance of your controller on $scope
under a property named view
, eg : ng-controller="ViewCtrl as view"
功能的作用是在$scope
的名为view
的属性下发布控制器的实例,例如:
Since $scope.view
is an instance of your controller and panelShowHide()
a function on your controller object, the 'owner' of panelShowHide()
function is the controller instance and hence this
points to it. 由于
$scope.view
是你的控制器的一个实例panelShowHide()
控制器对象的功能,的“所有者” panelShowHide()
函数是控制器实例,因此this
指向它。
When you enter a new function, you must always be suspicious of the value of this
. 输入新功能时,您必须始终对
this
的值感到怀疑。 Try this: 尝试这个:
var app = angular.module("myapp");
app.controller("ViewCtrl", function($scope) {
var self= this;
self.panelVisible = true;
self.panelShowHide = function() {
self.panelVisible = !self.panelVisible;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.