javascript - 为什么 $scope 和 'this' 关键字在 Controller 内可以互换使用?

标签 javascript angularjs angularjs-scope

我正在学习 Angular 的基础知识,对 Controller 、指令、范围、模型等知之甚少。在视频中,导师是这样编写 Controller 的:

var module = angular.module('name', [dependencies])
                    .controller($scope)...

我希望您从上面的代码片段中选择的唯一一件事是,他(导师)将 $scope 对象传递给 Controller ​​的函数。这很好,而且很有效。

在 Angular 官方网站的示例中,我发现了以下代码:

angular.module('invoice1', [])
.controller('InvoiceController', function() {
  this.qty = 1;
  this.cost = 2;
  this.inCurr = 'EUR';
  this.currencies = ['USD', 'EUR', 'CNY'];
  this.usdToForeignRates = {
    USD: 1,
    EUR: 0.74,
    CNY: 6.09
  };

我可以清楚地看到,在这个例子中,没有 $scope正在通过并且 this被用来代替。这是否意味着 $scope传递给 Controller ​​函数和 Controller 函数内的“this”是相同的对象吗?

最佳答案

这里有很多不同的东西。

在第一个代码片段中,您将创建一个名为“invoice1”的模块。该模块不注入(inject)任何第三方库或其他模块,因此为空[]。

之后,您将创建一个 Controller 。该 Controller 正在从 Angular 库注入(inject) $scope。

在第二个片段中,导师使用 controllerAs syntax 。所以你不需要$scope,而是可以直接将你的对象绑定(bind)到 Controller 。在 View 内部,您可以使用 Controller 的名称来引用绑定(bind)。

<div ng-controller="InvoiceController as invoice">
  {{ invoice.qty }}
</div>

关于javascript - 为什么 $scope 和 'this' 关键字在 Controller 内可以互换使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36981380/

相关文章:

javascript - AngularJS 指令 - 将属性值链接到范围属性

javascript - AngularJS 使用子 $state Controller 向父级范围内的对象添加属性

javascript - VueJS 调度函数的执行顺序导致问题

javascript - React DropzoneComponent 在上传之前在本地打开/修改文件

javascript - 如何为选择选项分配默认值

javascript - 处理非 Angular 代码时如何立即更新 $scope?

AngularJS Controller $scope 保留关键字?

javascript - 从 Mozilla Firefox 中的网页中获取 HTML 超出选择/范围

javascript - 如果找到数组中的元素,如何将其添加到数组中?

AngularJS 错误 : Unknown provider: $animateProvider <- $animate