什么'var vm = this;' 角度控制器意味着什么

Ram*_*iar 24 angularjs

我正在浏览github上的一些东西,我在controller.js中看到,有人放了以下内容:

function ImageController ($scope, $timeout) {
   var vm = this;
}
Run Code Online (Sandbox Code Playgroud)

这是用来做什么的?

Fed*_*kin 46

vm这种情况下表示viewmodel.

这是一个捷径,所以不用写,this.someMethod()你可以使用vm.someMethod().

当你使用Controller As语法时很常见,所以不要使用$scopeby"accident".

此外,this关键字可能很难使用,因为它可能会根据使用位置引用不同的内容.


Poy*_*maz 6

为什么?:有助于避免在控制器中使用$ scope方法的诱惑,否则可能更好地避免它们或将方法移动到工厂,并从控制器引用它们.

你可以查看完整的John Papa Angular Style来深入学习......