如果没有孩子,则删除tr - ng-repeat - angular

时间:2014-09-25 09:42:58

标签: javascript angularjs

我正在尝试使用ng-repeat在表中构建tr,并且我使用行作为值基于某些逻辑构建它。这是引入空tr我怎么能删除它?

此代码在tbody的末尾添加了2个空tr。

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

$scope.data = [
{
    "name" : "John",
    "row" : 1
},
 {
    "name" : "Mike",
    "row" : 2
},
 {
    "name" : "Bill",
    "row" : 1
},
{
    "name" : "Alice",
    "row" : 3
},
{
    "name" : "David",
    "row" : 2
}
 ]
 });



app.directive('specrow', ['$compile', function($compile) {
return {
  restrict: 'A',
    scope : {
      'specobj' : '=',
      'specitemindex' : '='
    },
    link: function (scope, elem, attrs){
      var template = "<td><span>{{specobj.name}}</span></td>";
        var linkFn = $compile(template);
        var content = linkFn(scope);
        var trEl = angular.element(elem[0].parentElement.children).eq(scope.specobj.row-1);
        if(trEl.length === 0) {
          elem.append(content);
        }else{
          angular.element(elem[0].parentElement.children).eq(scope.specobj.row-1).append(content);
        }  
    }
  }
}]);

Plnkr:http://plnkr.co/edit/I3kl9U41n3VzQvqFfG4G?p=preview

1 个答案:

答案 0 :(得分:1)

所以答案是:)

&#13;
&#13;
var app = angular.module('app', ['angular.filter']);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.data = [
    {
        "name" : "John",
        "row" : 1
    },
     {
        "name" : "Mike",
        "row" : 2
    },
     {
        "name" : "Bill",
        "row" : 1
    },
    {
        "name" : "Alice",
        "row" : 3
    },
    {
        "name" : "David",
        "row" : 2
    }
  ]
});
&#13;
table, th, td {
   border: 1px solid black;
} 
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.1.1/angular-filter.min.js"></script>

<body ng-app="app">
    <table ng-controller="MainCtrl">
      <tbody>
          <tr ng-repeat="row in data |groupBy: 'row' | orderBy : 'row'">
          <td ng-repeat="person in row">{{person.row}}.{{person.name}}</td>
              
          </tr>
      </tbody>
    </table>
  </body>
&#13;
&#13;
&#13;