2016-05-04 27 views
1

所以我正在看一個在1.5版中保持尖角的代碼學習的例子。 繼承人的代碼:爲什麼我們在角度中設置控制器變量等於「this」?

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

我讀了Mozilla的開發者網絡指南[這裏] [1],但我的理解仍然不是很大。

從以上示例的以下行中。

var controller = this; 

我們爲什麼要設置控制器=這個?爲什麼不只是有var控制器;?或者將它設置爲等於這使得它成爲一個全局變量,否則在成功回調中,它只會改變它自己的本地控制器變量而不是控制器中聲明的變量。

他們後來做以下的HTML如果它提供的線索:

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

回答

2

爲什麼不只是有var控制器;?

因爲這意味着controller將是undefined

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

是通過將其設置等於這使其成爲一個全局變量

你沒有創建一個全球變量而是要創建一個closed over變量。這意味着您可以在回調中使用該值。爲了在回調中使用該值,您需要創建一個閉包變量或綁定該函數。

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);

2

設置變量this允許你添加新的命名空間使用controllerAs語法時。

function OneCtrl() { 
    this.notes = "foo"; 
} 

function TwoCtrl() { 
    this.notes = "bar"; 
} 

HTML:

<div ng-controller="OneCtrl as ctrl1"> 
    {{ctrl1.notes}} 
    <div ng-controller="TwoCtrl as ctrl2"> 
     {{ctrl2.notes}} 
    </div> 
</div> 

沒有controllerAs,你必須做出的$parent使用,這實際上是不好的做法。成像必須使用$parent.$parent.$parent.$parent.someValue

延伸閱讀:http://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2015/07/02/exploring-angular-s-controller-as-syntax-and-the-vm-variable.aspx

1

是在成功的回調也只是改變了自己的本地控制器變量不是一個控制器宣佈將其設置等於這使其成爲一個全局變量,否則?

this的值取決於函數的調用方式。

當你有一個新的功能,你有一個新的價值this裏面。

將它存儲在另一個變量中意味着內部函數可以讀取該變量的值(因爲它不能訪問相同的this)。

這不是一個全球性的,只是一個更廣泛的範圍內的變量。

相關問題