2014-07-17 24 views
0

在我控制我分配:

$scope.currentThing.data 

而且在我的模板有時我需要

currentThing.data.response[0].hello 

有時

currentThing.data.otherStuff[0].goodbye 
//or 
currentThing.data.anotherThing[0].goodMorning 

所以我想知道如果可以直接在模板中爲這些變量創建一個快捷方式,例如:

{{response = currentThing.data.response[0]}} 

以便我可以像這樣使用它{{response.hello}}

通常,是否可以從模板中分配臨時變量?我不需要有任何的數據綁定,我需要他們僅用於生成模板,然後他們會永遠消失

回答

2

你可以做,在控制器喜歡這裏:http://jsbin.com/moyuhe/1/edit

app.controller('firstCtrl', function($scope){ 
$scope.currentThing = { 

    data: [ 

    {response:[ 
     {hello:1}, 
     {hello:2} 
    ]} 
    ] 

}; 
$scope.temp = $scope.currentThing.data[0]; 

}); 

HTML:

<div ng-controller="firstCtrl"> 
    {{temp.response |json }} 
     </div> 
0

您可能能夠使用ngInithttps://docs.angularjs.org/api/ng/directive/ngInit

看來雖然在之外使用它ngRepeat被皺起了眉頭。

<div ng-init="myvar = currentThing.data.response[0]"> 
    <span>{{myvar.hello}}</span> 
</div> 

我還沒有像這樣測試過,但這是我能想到的最接近的事情,可以解決您的問題。

+0

正如他們所說:'唯一的適當使用ngInit的是別名ngRepeat' – Leonardo

0

是的,有可能使用類似語法

{{ variable = (expression) }} 

在HTML模板的任何地方(不像一些建議的那樣只有ng-init)。

這對於需要多次使用計算變量的情況非常有用 - 無需每次計算。

一些示例

<!-- can use it before --> 
<p> Calculated value is {{calculated}} </p> 

<div ng-repeat=" item in calculated = (allItems | filter1 | filter2 | filter3) "> 
    {{item}} 
</div> 

<!-- can use it after--> 
<p> Calculated value is still {{calculated}} </p> 

編輯:所以你的情況 {{response = (currentThing.data.response[0]) }}

+0

的特殊性質我很想用這個解決方案,但它似乎不起作用在我的情況:'{{response =(currentThing.data.response [0])}}'throws「語法錯誤,無法識別的表達式」 – Leonardo