سؤال

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?

هل كانت مفيدة؟

المحلول

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")
];

نصائح أخرى

I guess you want to archive a master/detail view. You need to place the displaying of the details outside the ng-repeat. You also do not need an array for the details. Just use an object on the scope and assign it in getDetails.

http://jsbin.com/heyaqexa

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top