nikib3ro
nikib3ro

Reputation: 20606

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

Upvotes: 1

Views: 353

Answers (2)

Beyers
Beyers

Reputation: 9108

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

enter image description here

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.

Upvotes: 3

Steve H.
Steve H.

Reputation: 6947

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;
    }
});

Upvotes: 2

Related Questions