2015-10-01 79 views
0

這個ng-init變量'someData'到底存儲在哪裏?Angular:如果在ng-init中設置變量'存儲'在哪裏?

<tr data-ng-repeat="item in items" ng-init="someData=1"> 
<td>{{item.id}}</td> 
<td>{{someData}}</td> 
</tr> 

如何從外部訪問它,即從應該設置someData = someData + 1的函數訪問它?

+0

作爲正常的範圍 –

+0

按範圍你是指'項目'?我找不到它。對不起,我仍然在圍繞着來自C#背景的JS作用域。 – Vok

+0

https://docs.angularjs.org/guide/scope more $範圍 – shammelburg

回答

0

視圖中定義的變量的當前範圍限定。然而,知道你現在的範圍實際上並不總是那麼容易。您當前的範圍由創建範圍的最接近的元素決定。

簡單的情況下

如果你是直接在控制器內,然後你目前的範圍是控制器的$範圍變量。如下面的例子:

在HTML
<div ng-controller="MyController"> 
    <div ng-init="someData = 1"> 
    </div> 
</div> 
在myController的
$timeout(function() { 
    console.log($scope.someData); // Logs 1 
}) 

變量 「someData」 被上的myController的範圍所限定。請注意超時,因爲在解析視圖之前之前運行控制器,所以如果我們立即登錄,ng-init將不會運行,並且變量未定義。

如果你要窩兩個控制器,然後就NG-INIT裏面,它將會分配給最接近的一個。所以,如果你有控制器A和裏面,你有控制器B和你NG-INIT裏面,那麼它將會分配控制器B裏面的變量,而不是A.

越少simpel情況下

如果你嘗試上述解決方案與您的代碼是行不通的。原因是你正在使用中繼器。 ng-repeat,以及大多數其他指令將創建他們自己的範圍!在你的情況下someData將被定義在中繼器的內部範圍內,這是你的控制器無法訪問的!這是順便說一句,重複中的「item」變量存儲在該行的本地中繼器範圍中。轉發器中的每一行都會得到它自己的新範圍,這就是爲什麼每行都使用相同的「項目」變量,但每次都意味着不同的事情。

<div ng-controller="MyController"> 
    We are now in the scope of MyController. 
    Variables defined here can be find in $scope of MyController. 

    <div ng-repeat="foo in bar"> 
     We are now in the local repeater scope, one for each row. 
     Note that the containing div is part of the scope. 
     Variables defined here go on the local scope, MyController can't find them. 
    </div> 

    The repeater scope has ended, we are back in MyController 

    <div ng-include="someview.html"> 
     And now we are in the local scope of the ng-include! 
     This scope works just like the ng-repeat one does. 
    </div> 
</div> 

這與JavaScript中繼承的工作方式有關。請注意,如果你從哪裏得到,只有在家長存在的變量(比如將它打印出來),它會正常工作。在JavaScript中,當你得到一個變量時,它會繼續繼承鏈,直到它找到它。瓦努阿圖只要你嘗試分配值的東西它會創建它自己的局部變量,並從那時起使用該代替。

所以你的情況,你無法真正從控制器找到它(除非你送了它作爲參數傳遞給過程的函數),因爲父作用域不能訪問兒童範圍。

更好的方法

有一些方法可以解決這個問題。推薦的方法是使用控制器作爲語法。它在documentation for ng-controller中進行了描述,但總而言之,您將變量直接分配給控制器對象(而不是$ scope對象),然後在您的視圖中調用控制器時爲其命名。這可以讓你清楚你從哪個控制器獲得哪個變量。

在myController的
this.data = {}; 
在HTML
<div ng-controller="MyController as MC"> 
    <div ng-controller="item in items" ng-init="MC.someData = 1"> 
    </div> 
</div> 

既然你現在明確創建someData你的 「MC」 控制器上沒有更多的混亂。無論有多少指令或控制器嵌套,你都知道數據到底在哪裏。請注意,「item」仍然在中繼器範圍內,但這沒關係,因爲它應該在中繼器內部。如果你需要它,可以使用一個函數將它傳出,或者理論上在你的中繼器中使用ng-init。