1

If I have a controller such as:

myApp.controller('NewController', function ($scope, $window) {
   var x = 5;
   $scope.y = 5;
});

And x and y are going to be changed from my application, does it make any difference whether or not I declare var x on $scope or just declare it with var as it is right now?

Startec
  • 12,496
  • 23
  • 93
  • 160
  • 2
    Yes, it does make a difference. Someone looking at your code needs to know which are internal "private" variables and which are exposed as "public" on your view. – Blunderfest Feb 08 '16 at 13:06

4 Answers4

5

$scope is just the glue between your rendered view and your controller. If you don't need the variable in your view, then don't add it to the $scope object.

dendimiiii
  • 1,659
  • 3
  • 15
  • 26
2

It all depends upon the application that you are developing. If one wishes to bind the variables with that of the view via the controller, then $scope is preferred. Otherwise, when the variable is meant for some internal functionality only, then one should use JavaScript's var as it will not hinder the performance when making use of AngularJS framework, by adding unnecessary variables that aren't required at all for either for two-way binding or one-way binding.

Shashank
  • 2,010
  • 2
  • 18
  • 38
0

it's better to use new ControllerAs syntax and not to use $scope at all:

myApp.controller('NewController', function ($scope, $window) {
    this.y = 5;
});

for native JS it's pretty clear that you don't need var before "this", right?

Stepan Suvorov
  • 25,118
  • 26
  • 108
  • 176
0

It's depands on you if you bind the value with any html dom that should be change when you are changing your model then you should use $scope. otherwise you can use var and $scope. but now in angular 2.0 $scope has removed.