简体   繁体   English

AngularJS按索引过滤ng-repeat?

[英]AngularJS filter ng-repeat by index?

I have a table and buttons inside a loop, this picture shows the results of what I get depending on the search 我在循环中有一个表格和按钮,此图显示了根据搜索得到的结果

在此处输入图片说明

html 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 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;});
        }
}

When I click on the comment Button I want to display the comments according to that ID. 当我单击评论按钮时,我想根据该ID显示评论。 This is working fine except that the comments are loaded to all tables and not only to the table with the right ID. 除了将注释加载到所有表而且不仅加载到具有正确ID的表上之外,此方法都工作正常。 In this example I clicked on ID 1 Coka Cola. 在此示例中,我单击了ID 1可口可乐。 在此处输入图片说明

Where do I need to apply a filter the js or html? 我需要在哪里应用js或html过滤器? both? 都? ... ...

![enter image description here][3]stack.imgur.com/gqyPR.jpg ![在此处输入图片描述] [3] stack.imgur.com/gqyPR.jpg

You can simply bind your comments with your product's id in order to make it unique for each product. 您只需将comments与产品ID绑定在一起,以使其对每个产品都是唯一的。

What we need to do is to add product's id to $scope.comments as following: 我们需要做的是将产品的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;});
        }
}

Then, you can simply loop through it: 然后,您可以简单地遍历它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM