0

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.

mustafa1993
  • 541
  • 1
  • 5
  • 17
  • Possible duplicate of [How does the "this" keyword work?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Karan Desai Sep 15 '16 at 06:12

2 Answers2

2

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.

Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889
1

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

rick
  • 1,869
  • 13
  • 22
  • Yes I got it. Thanks. Just that in OO programming we say new on constructor that belongs to a class. Here we have just the function. Where does class fit in here? – mustafa1993 Aug 04 '16 at 09:21
  • 1
    @mustafa Javascript doesn't have classes, it only has objects and functions. "Class" behaviour is realised with the behaviour of the `this` and `new` keywords and `prototype`. It's just as "OO" as class based OO, arguably even more so, since *everything* is an object. This is not the appropriate place to expand on that though, there is more than enough discussion about this already. – deceze Aug 04 '16 at 09:35
  • Yeah, now I know what to search for regarding this. – mustafa1993 Aug 04 '16 at 10:02