0

Can someone explain the different between two variables a1 and a2:

app.controller("someCtrl",function(){
  this.a1=somevalue;
  var a2=somevalue;
});

And what lifetime a2 has?

kliukovking
  • 569
  • 1
  • 5
  • 16

2 Answers2

2

They are similar. Same lifetime however this.a1 has model bindings (which is fundamental within angular applications if you're going to use this variable anywhere in your view) where as a2 doesn't and you won't be able to access it using $scope within the view.

Adrian
  • 8,271
  • 2
  • 26
  • 43
  • I don't using $scope at all. So as I understand, all the different is a1 is available in view, and a2 doesn't, right? – kliukovking Jul 17 '17 at 10:09
  • Yes. That's basically all. this inherits controller properties too i.e. it can be accessed in $rootScope etc. If you don't need to access it anywhere except that controller I would stick to var declaration. – Adrian Jul 17 '17 at 10:33
1

Simply speaking, this.a1 will create a property called a1 on whatever object this refers to when invoking the controller function. Since you are invoking the constructor function, this will refer to the controller itself, so you will be able to use a1 for data-binding. var a2 will create a local variable called a2 inside the function.

Kapol
  • 6,383
  • 3
  • 21
  • 46