2013-09-27 15 views
0

我正在製作一個瀏覽頁面,用戶可以在其中查看我站點搜索構面的頂部術語(我正在使用ElasticSearch/Tire)。我創建了一個對象數組,一個標題和我需要搜索的格式的參數。我想遍歷數組並顯示標題,然後顯示每個方面的搜索結果。起初,我嘗試在控制器中使用for循環遍歷facet_selections,但這看起來並不像Angular方式。所以現在我試圖在迭代中使用ng-repeat,但我不確定如何將視圖中的參數傳遞給控制器​​。我閱讀了所有的指令,我看不出合適的,這讓我覺得我可能一起走錯了路。如何將變量從視圖傳遞到作用域使用ngRepeat

下面是一個簡單的控制器:

$scope.facet_selections=[{name:"Collection", value: "collection_title", term: "collectionTitle"}, {name:"Series", value: "series_title", term: "seriesTitle"}, {name:"Episode", value: "episode_title", term: "episodeTitle"},]; 

$scope.frequency=Frequency.query({facet: facet}).then(function(data) { 
    $scope.topterms=data.facets[term].terms; 
}) 

而這裏的HTML:

<div class="browse" ng-repeat="object in facet_selections" ng-init="var term={{object.term}}"> 
    <h4> {{object.name}} </h4> 
    <ul> 
     <li ng-repeat="term in topterms"> {{term.term}} ({{term.count}})</li> 
    </ul> 
</div> 
+0

什麼說法是你想通過? – Fresheyeball

+0

我試圖將'facet'(facet_selections.value)和'term'(facet_selections.term)傳遞給$ scope.frequency。 –

回答

0

的問題是,你不能在HTML綁定到一個承諾。你必須等待承諾解決然後更新範圍。所以我會處理控制器中的初始循環,而不是使用ng-repeat

$scope.facet_selections=[{name:"Collection", value: "collection_title", term: "collectionTitle"}, {name:"Series", value: "series_title", term: "seriesTitle"}, {name:"Episode", value: "episode_title", term: "episodeTitle"},]; 

for(var i; i < $scope.facet_selections.length; i++){ 
    var selection = $scope.facet_selections[i]; 
    Frequency.query({facet: selection.value}).then(function(data) { 
     $scope.facet_selections[i].results = data.facets[selection.term].terms; 
     $scope.$digest() // hook into the angular binding system 
    }); 
} 

然後

<div class="browse" ng-repeat="facet in facet_selections"> 
    <h4> {{facet.name}} </h4> 
    <ul> 
     <li ng-repeat="term in facet.results"> {{term.term}} ({{term.count}})</li> 
    </ul> 
</div> 
從視圖到控制器

傳輸參數是非常容易的:

$scope.numbers = [0, 4, 5, 2]; 
$scope.getTimesTwo = function(num){ 
    return num * 2; 
}; 

然後

<div ng-repeat="num in numbers"> 
    {{num}} <span>{{getTimesTwo(num)}}</span> 
</div> 

將導致

<div ng-repeat="num in numbers"> 
    0 <span>0</span> 
</div> 
<div ng-repeat="num in numbers"> 
    4 <span>8</span> 
</div> 
<div ng-repeat="num in numbers"> 
    5 <span>10</span> 
</div> 
<div ng-repeat="num in numbers"> 
    2 <span>4</span> 
</div> 

它只是是不是真的是你的問題,其解決的承諾掛鉤的$digest週期

+0

謝謝,這真的很有幫助,我認爲它接近工作。 '$ scope.facet_selections [i] .results'應該如何工作?我認爲你可能意味着'$ scope.facet_selections [i] .value.results',以便它像'$ scope.collection_title.results'一樣創建一個新的作用域,但這似乎不起作用。 –

+0

with'$ scope.facet_selections [i] .results'我只是隨意地將結果附加到'$ scope.facet_selections'中以使我的生活更輕鬆。 'value.results'也很好。我不知道'$ scope.collection_title'是什麼,所以我不能評論。如果你發現這有幫助,那麼upvote怎麼樣? – Fresheyeball

+0

顯然我還沒有足夠積分upvotes,但我會愉快地做綠色檢查,一旦我有這種排序。我返回結果,但它們都是'facet_selections'中的最後一個對象。似乎我可能需要給他們唯一的變量名稱。 –

相關問題