mustafa1993
mustafa1993

Reputation: 561

What exactly 'this' means in AngularJS controller?

index.html

 <body ng-controller="StoreController as s">
  <h1 ng-click="s.changeValFunc()">{{s.carname}}</h1>
  <h2>{{s.carname}}</h2>
  </body>

app.js

var app = angular.module('store', []);
app.controller('StoreController', function() {
    this.carname = "Volvo";
    this.changeValFunc = function(){
        this.carname="BMW";
    }
});

Clicking on h1 tag changes {{carname}} for both h1 and h2 to BMW. Isn't it "this" refers to the current element being clicked. Am confused on how controller properties are shared among views.

Upvotes: 0

Views: 63

Answers (2)

rick
rick

Reputation: 1895

In your case this refer to the controller itself.

So any attribute in that controller can be accessed with

this.attribute

In your case you "assign" the controller to a parent element

<body ng-controller="StoreController as s">

This mean that you create an instance of StoreController for the element body.

Changing the attribute carname you change it for the entire controller.

If you know littlebit of OO programming you can see the controller as a Class and with this you refer the instance of the class.

This is true for your case, in javascript this has some strange behaviour sometimes.

As said by deceze you can take a look at some posts that explain how this works in JS.

hope this helps

Upvotes: 1

deceze
deceze

Reputation: 521995

The controller function is instantiated with new. That means it works like this:

function StoreController() {
    this.carname = "Volvo";
    this.changeValFunc = function () {
        this.carname="BMW";
    }
};

var s = new StoreController();

console.log(s.carname); // Volvo

The s in your view is a reference to the instantiated StoreController, which has those attributes, because you put them there in the constructor function. You might want to see How does the "this" keyword work? for details.

Upvotes: 2

Related Questions