javascript - 为什么我们在 Angular 上将 Controller 变量设置为 "this"?

标签 javascript angularjs this

因此,我在 1.5 节中查看了代码学校中保持尖锐和 Angular 示例。 继承人的代码:

angular.module('NoteWrangler')
.controller('NotesIndexController', function($http) {
    var controller = this;
    $http({method: 'GET', url: '/notes'}).success(function(data){
        controller.notes = data;
    })
 });

我阅读了 Mozilla 的 [this][1] 开发者网络指南,但我的理解仍然不是很好。

在上面示例的以下行中。

var controller = this;

为什么我们要将 controller = 设置为此?为什么不只使用 var controller;? 或者通过将其设置为等于此值使其成为全局变量,否则在成功回调中只会更改其自己的本地 Controller 变量,而不是在 Controller 中声明的变量?

如果提供任何线索,他们随后会在 html 中执行以下操作:

<div class="note-wrapper">
    <a class ="card-notes" ng-repeat="notes in indexController.notes">
    </a>
</div>

最佳答案

Why not just have var controller;?

因为这意味着 controller 将是 undefined

var controller;
document.querySelector('pre').innerHTML = controller;
<pre></pre>

is by setting it equal to this making it a global variable

您不是在创建一个全局 变量,而是在创建一个closed over。多变的。这意味着您可以在回调中使用该值。为了在回调中使用该值,您需要创建闭包变量或绑定(bind)函数。

var controller = {
  hello: 'world'
};

// Just so we have to use a callback
setTimeout(function() {
  console.log(this);
}, 0);

// Using a closure variable
setTimeout(function() {
  console.log(controller);
}, 0);

// Binding a function
setTimeout(function() {
  console.log(this);
}.bind(controller), 0);

关于javascript - 为什么我们在 Angular 上将 Controller 变量设置为 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37032618/

相关文章:

javascript - 两个谷歌饼图中只有一个显示

javascript - 为什么我的博客上有不需要的 css 和 js 文件?

javascript - 在 WordPress 中使用 Angular 获取 JSON 内容

javascript - AngularJS JSON 对象在 View 中可访问,但在 Controller 中不可访问

C++ 在非成员函数中无效使用 'this'

javascript - 如何遍历 JavaScript 中的对象数组?

javascript - Firefox 4 onBeforeUnload 自定义消息

angularjs - ionic 框架中的月份和年份选择器

javascript - 在不使用 "this"的情况下在对象中定义 JavaScript get 和 set 函数?

javascript - 为什么我不能使用 $(this) jQuery 选择器