控制器中此范围与范围之间的差异

Joh*_*Doe 10 angularjs angularjs-scope

我是angularjs的新手.如果将函数分配给$ scope或控制器中的此关键字,有什么区别?谢谢.

示例(范围):

.controller('TestCtrl', ['$scope', function ($scope) {
    $scope.testFunc = function () {
    };
}]);
Run Code Online (Sandbox Code Playgroud)

示例(本)

.controller('TestCtrl', [function () {
    var app = this;
    app.testFunc = function () {
    };
}]);
Run Code Online (Sandbox Code Playgroud)

Cét*_*tia 10

$scope是角度框架和双重数据绑定功能的核心概念.例如,旨在与以下内容分享其内容:

  • 模板
  • 指令
  • 等等

例如,在模板中,您需要将函数绑定scope到访问它.您将无法this直接调用绑定的功能.


编辑:感谢BKM的帖子,指出这种行为可以通过"控制器为"语法将模板直接绑定到控制器.但是由您决定是否要在模板中访问控制器的所有对象/变量而不是使用专用viewModel(scope).有关优缺点,请参阅:https://groups.google.com/forum/#!topic / angular/84selECbp1I


这是一个重要的角度概念,你需要了解.

见:

thiskeywork仅指javascript引用object你的controller,仅此而已.


BKM*_*BKM 8

比西说错了.没有必要将函数绑定到范围以便访问它.

Angular JSie 的最新版本中,1.2他们引入了一个新的关键字controllerAs,使得可以不在控制器内部使用范围.

<div ng-controller="testCtrl as test">
    {{test.value}}
</div>
Run Code Online (Sandbox Code Playgroud)

并在你的控制器

app.controller('testCtrl ', function () {
   this.value = 'Hello World';
});
Run Code Online (Sandbox Code Playgroud)

看到上面的控制器是在没有注入的情况下生成的$scope.

是一个很好的视频教程解释这个