![](/img/trans.png)
[英]AngularJS : Not able to access controller's scope variable inside $scope.$on
[英]AngularJS scope of controller variable depending on if it's attached to scope or this
我有以下控制器定義:
var app = angular.module("myapp");
app.controller("ViewCtrl", function($scope) {
this.panelVisible = true;
this.panelShowHide = function() {
this.panelVisible = !this.panelVisible;
}
});
這是我的看法:
<body ng-controller="ViewCtrl as view">
<a href="" ng-click="view.panelShowHide()">Button</a>
{{view.panelVisible}}
</body>
從我的角度來看,我正在調用panelShowHide函數,與我的預期相反, this.panelVisible = !this.panelVisible
行以某種方式更新了控制器變量(在this.panelVisible = true;
行中定義)
那怎么可能? 我知道我是否執行了$scope.panelVisible
,但是由於我正在panelShowHide函數中執行this.panelVisible
,因此該行是否不應該在函數范圍內創建和更新定義的新變量?
我問這個問題是為了更好地理解AngularJS的范圍,因為在一些更復雜的情況下(例如使用$ http.get),我的this.reference是“正確解析的”(局部變量),我希望能夠引用控制器變量(封裝邏輯)。
ng-controller="ViewCtrl as view"
功能的作用是在$scope
的名為view
的屬性下發布控制器的實例,例如:
由於$scope.view
是你的控制器的一個實例panelShowHide()
控制器對象的功能,的“所有者” panelShowHide()
函數是控制器實例,因此this
指向它。
輸入新功能時,您必須始終對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.