I know that I should keep my controllers lean & mean, but if I do need a variable which will not be reflected in the view, should I declare it in $scope. or as var?
1 Answer
I declare them as var if I dont need two-way binding. When you put your data into $scope, you put a watch on them (and with this put it in the angular digest cycle) and that's redundant if you dont need to use the variable in the view. Simple rule: Don't use $scope if you dont need angular to update the view with it.
2 Comments
ivarni
+1, but I'd like to change the rule to
always use the smallest possible scope when declaring a variable. IMO that's a universally good idea for every language/framework.Mawg
Thanks, I had thought to use
var. But, f.y.i, I am working my way through ng-book (ng-book.com) and it says that Angular will NOT put a watch on any scope variable that is not in the view (in fact, it doesn't need to watch {{myScopeVar}} only ng-model="myOtherScopeVar" which it is required to watch n order to provide two-way data binding). I still think var, though.