2016-09-26 69 views
-1

我不善於解釋我希望你們瞭解我的需求並幫助我在這裏。angularjs從控制器的值動態顯示錶達式

我具有低於

<div ng-repeat="item in allitems"> {{displaydata}} </div> 

與NG-重複的圖我有以下數據的控制器

$scope.allitems ={ 
1:{name:"car",price:"999",qty:8}, 
2:{name:"bag",price:"127",qty:2}, 
3:{name:"dog",price:"777",qty:3}, 
4:{name:"cat",price:"333",qty:4} 
} 
var displaychoice1 = "{{item.name}}" 
var displaychoice2 = "{{item.price}}" 
$scope.displaydata = "I want " + displaychoice1 + " which cost " + displaychoice2 ; 

我希望用戶能夠選擇「田」,以輸出到而不是硬編碼在視圖中顯示的內容。

+0

那麼,只要去'

I want {{item.name}} which cost {{item.name}}
' 或者你究竟需要什麼? –

+0

這個'ng-repeat'甚至不會像書面那樣工作;此模式對於對象無效。 'allitems'必須是一個數組。 – Claies

回答

1

$scope.allitems應該是一個array

$scope.allitems = [ 
    {name:"car",price:"999",qty:8}, 
    {name:"bag",price:"127",qty:2}, 
    {name:"dog",price:"777",qty:3}, 
    {name:"cat",price:"333",qty:4} 
] 

而上的HTML,你可以簡單地

<div ng-repeat="item in allitems"> 
    I want {{item.name}} which cost {{item.price}} 
</div> 

編輯

允許用戶選擇字段可以像

在控制器:

$scope.displaydata = function(item, field1, field2){ 
    return "I want " + item[field1] + " which cost " + item[field2]; 
} 

在HTML:

<div ng-repeat="item in allitems"> 
    {{ displaydata(item, 'name', 'price') }} 
</div> 

在那裏你能適應nameprice來自變量,你已經

+0

謝謝taguenizy –

+0

非常感謝,我正在尋找 –

0

可以使用ngoptions它允許用戶選擇選項:

<select name="mySelect" id="mySelect" 
     ng-options="item in allitems track by $index" 
     ng-model="selectedOption"> </select> 

I want {{selectedOption.name}} which cost {{selectedOption.price}}