简体   繁体   中英

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

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

When I click on the comment Button I want to display the comments according to that ID. This is working fine except that the comments are loaded to all tables and not only to the table with the right ID. In this example I clicked on ID 1 Coka Cola. 在此处输入图片说明

Where do I need to apply a filter the js or html? both? ...

![enter image description here][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.

What we need to do is to add product's id to $scope.comments as following:

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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