Adding rows with ng-repeat and nested loop

前端 未结 6 922
情书的邮戳
情书的邮戳 2020-12-02 15:25

I\'m looking for a way to add rows to a table. My data structure looks like that:

  rows = [
    { name : \'row1\', subrows : [{ name : \'row1.1\' }, { name          


        
6条回答
  •  独厮守ぢ
    2020-12-02 16:00

    I'm a bit surprised that so many are advocating custom directives and creating proxy variables being updated by $watch.

    Problems like this are the reason that AngularJS filters were made!

    From the docs:

    A filter formats the value of an expression for display to the user.
    

    We aren't looking to manipulate the data, just format it for display in a different way. So let's make a filter that takes in our rows array, flattens it, and returns the flattened rows.

    .filter('flattenRows', function(){
    return function(rows) {
        var flatten = [];
        angular.forEach(rows, function(row){
          subrows = row.subrows;
          flatten.push(row);
          if(subrows){
            angular.forEach(subrows, function(subrow){
              flatten.push( angular.extend(subrow, {subrow: true}) );
            });
          }
        });
        return flatten;
    }
    })
    

    Now all we need is to add the filter to ngRepeat:

    Rows with filter
    {{row.name}}

    You are now free to combine your table with other filters if desired, like a search.

    While the multiple tbody approach is handy, and valid, it will mess up any css that relies on the order or index of child rows, such as a "striped" table and also makes the assumption that you haven't styled your tbody in a way that you don't want repeated.

    Here's a plunk: http://embed.plnkr.co/otjeQv7z0rifPusneJ0F/preview

    Edit:I added a subrow value and used it in the table to show which rows are subrows, as you indicated a concern for being able to do that.

提交回复
热议问题