0

我正在创建一个浏览页面,用户可以在其中看到我网站搜索方面的热门术语(我正在使用 ElasticSearch/Tire。)我创建了一个对象数组,其中包含我需要搜索的格式的标题和参数。我想遍历数组并显示标题,然后显示我对每个方面的搜索结果。起初我尝试在控制器中使用 for 循环来迭代facet_selections,但这似乎不像 Angular 方式。所以现在我正在尝试使用 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"},];

$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>
4

1 回答 1

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循环挂钩

于 2013-09-27T22:25:13.270 回答