Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: ng-repeat for a specific "ID"?

first of all, I'm quite new to angularJS, so be gentle! Second, I know there are no "ID"s, "class"es etc. in angularJS so the title might be somewhat misleading. However, I failed to describe the issue any better.

Here's the deal: I have an array of elements, and each has its details. Now, I ng-repeat the first set of elements to show the basic info. And when user clicks "details", the corresponding details are loaded. Yet, in my case, each item gets the details of a selected element.

The case in practice: http://jsbin.com/zilayija/2/edit

Is there any way to append the corresponding details to the ones that match Id ONLY?

like image 793
user3588536 Avatar asked Sep 20 '26 23:09

user3588536


1 Answers

The real issue here is that you're binding the details to a single array on your $scope, namely details. As this reference is used in each iteration of the ng-repeat, you'll end up showing it everywhere.

Edit: As mentioned in the comments, the original question did not reflect what was actually asked. What was requested was that the details needed to be loaded in asynchronously and only when they were requested (clicked). I therefore updated the code example).

What changed?

HTML:

<li ng-repeat="item in items">
    {{item.name}}
    <a href="" ng-click="item.showDetails()">show details</a>
    <p ng-show="item.detailsVisible" ng-repeat="detail in getDetails(item.id)">
        {{detail.belongsToItem}}
    </p>
</li>

JS:

var Item = function(id, name){
    var promiseDetailsAreLoaded;
    var self = this;

    this.id = id;
    this.name = name;
    this.detailsVisible = false;
    this.details = [];
    this.showDetails = function(){
        if(!promiseDetailsAreLoaded){
          promiseDetailsAreLoaded = $http.get("").then(function(){
              // mock adding details
              for(var i = 0; i < itemDetails.length; i++){
                  if(itemDetails[i].belongsToItem === self.id){
                      self.details.push(itemDetails[i]);
                  }
              }
          });
        }
        promiseDetailsAreLoaded.then(function(){
            self.detailsVisible = !self.detailsVisible;  
        });
    }
};

$scope.items = [
  new Item(1, "Item 1"),
  new Item(2, "Item 2"),
  new Item(3, "Item 3")
];
like image 88
thomaux Avatar answered Sep 23 '26 11:09

thomaux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!