AngularJS按指数过滤ng-repeat?

时间:2014-12-13 15:47:24

标签: angularjs filter ng-repeat

我在循环中有一个表和按钮,这张图显示了我根据搜索得到的结果

enter image description here

HTML

     <div class="col-sm-4" ng-repeat="x in names">
        <div class="panel panel-primary"  id= "{{ x.myIndex }}" >
            <div class="panel-heading">
              <h3 class="panel-title">{{ x.ID }} {{ x.Name }}
      <button ng-click="showCommentsWithID(x.ID)"  style="float: right;" class="btn btn-xs btn-primary glyphicon glyphicon-comment"> 42</button>

                </h3>
                </div>
        <div class="panel-body">

     <table width="" border="0" ng-repeat="c in comments"  id= "{{ c.ID}}" ">
                      <tr>
                        <td width="30">{{ c.ID }}</td>
                        <td >{{ c.Comment}}</td>
                      </tr>
      </table>

        </div>
          </div>
          </div><!-- /.col-sm-4 -->

JS

function ContactController($scope,$http) {
$scope.showCommentsWithID= function(myID) { 
                    var page = "mySQL.php?func=getComments&id=" + myID;
                    $http.get(page).success(function(response) {$scope.comments = response;});
        }
}

当我点击评论按钮时,我想根据该ID显示评论。 除了将注释加载到所有表而不仅仅加载到具有正确ID的表之外,这样工作正常。在这个例子中,我点击了ID 1 Coka Cola。  enter image description here

我需要在哪里应用js或html过滤器?都? ...

![在此输入图片说明] [3] stack.imgur.com/gqyPR.jpg

1 个答案:

答案 0 :(得分:2)

您只需将comments与产品的ID绑定即可,以使每种产品都具有唯一性。

我们需要做的是将产品的ID添加到$scope.comments,如下所示:

function ContactController($scope,$http) {
        $scope.comments = {}; // Init comments object.
        $scope.showCommentsWithID= function(myID) { 
                    var page = "mySQL.php?func=getComments&id=" + myID;
                    $http.get(page).success(function(response) {$scope.comments[myID] = response;});
        }
}

然后,你可以简单地遍历它:

 <table width="" border="0" ng-repeat="c in comments[x.ID]"  id= "{{ c.ID}}" ">
     <tr>
         <td width="30">{{ c.ID }}</td>
         <td >{{ c.Comment}}</td>
     </tr>
 </table>