简体   繁体   中英

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)

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?

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).

What the ng-controller="ViewCtrl as view" feature does is publish an instance of your controller on $scope under a property named view , eg :

在此处输入图片说明

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.

When you enter a new function, you must always be suspicious of the value of 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;
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM