$scope vs var in AngularJS

后端 未结 5 1845
暖寄归人
暖寄归人 2020-12-05 17:38

I\'ve been using var and $scope.varname and both work fine in AngularJS. I was wondering if there was a difference between the two functionally, and what best practice was i

5条回答
  •  感情败类
    2020-12-05 17:55

    The technical implications of using var and $scope have been described by @tymeJV and others. I think the next logical question answer is: When do I use either?

    TL;DR - if you do not use a variable in a view (e.g. {{myVar}} ), use var.

    The reason is two fold:

    1. Encapsulation - hide state that is not necessary to the view. This will prevent unintended modifications of the variable.

    2. Performance (prevent extra digest cycles) - Angular performs "dirty state" checking on variables. Modifying a variable that's not used in the view may cause extra digest cycles unnecessarily. In an application with a couple of ng-repeats and a bunch of watches, this can have a huge impact.

提交回复
热议问题