Tower Jimmy
Tower Jimmy

Reputation: 567

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

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

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

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

![enter image description here][3]stack.imgur.com/gqyPR.jpg

Upvotes: 0

Views: 190

Answers (1)

lvarayut
lvarayut

Reputation: 15259

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>

Upvotes: 2

Related Questions