Home Ask Login Register

Developers Planet

Your answer is one click away!

Startec February 2016

Should I declare "var" variables in an Angular controller or always use $scope

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?


dendimiiii February 2016

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

STEVER February 2016

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?

Shashank February 2016

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.

vipin Bhandari February 2016

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.

Post Status

Asked in February 2016
Viewed 1,460 times
Voted 6
Answered 4 times


Leave an answer

Quote of the day: live life