2016-08-22 53 views
0

我正在尝试使用angularJS打印出一些数据。下面是脚本的相关段:由ng-repeat创建的额外div

$scope.incidentCats = [{ 
    name: "FIRE", 
    incidents: [{ 
    location: "location 1", 
    dateTime: "datetime 1", 
    currStatus: "currStatus 1" 
    }, 
    { 
    location: "location 2", 
    dateTime: "datetime 2", 
    currStatus: "currStatus 2" 
    }] 
}, 
{ 
    name: "CODE BLUE", 
    incidents: [{ 
    location: "location 3", 
    dateTime: "datetime 3", 
    currStatus: "currStatus 3" 
    }] 
}]; 

正如你可以在数据看,事件类型FIRE有两个事件的记录,而事件类型CODE BLUE只有一个。

这里是在EJS文件中的相关代码:

<div ng-repeat="category in incidentCats" class="incident"> 
    <header class="category"> 
    <strong>{{ category.name }}</strong> 
    </header> 
    <section> 
    <div ng-repeat="incident in category.incidents"> 
     {{ incident.location }}<br> 
     {{ incident.dateTime }}<br> 
     {{ incident.currStatus }}<br> 
    </div> 
    </section> 
</div> 

最后,这是我的HTML的这个特定部位(不包括用于整个项目,是从我手中的公用CSS)CSS:

.incident { 
    width: 100%; 
    height: 100%; 
    border: 1px solid #fff; 
    position: relative; 
    padding: 5px; 
    margin: 25px 0; 
} 

.incident section { 
    margin-top: 10px; 
} 

.incident section > div { 
    margin: 5px auto; 
} 

到目前为止,代码工作预期,除了一两件事:当事件循环中创建了div元素,我期待2 divFIRE类别中创建,只有一个divCODE BLUE类别。但是,代码为这两个类别创建了两个div

这不是我想要的。由于第二个divCODE BLUE中包含<br>标签但没有数据,因为此类别的记录中没有第二次事件,所以现在有一段空白空间,其中第二个div位于第一个div之下,这很好因为第一个事件确实存在并被正确打印出来。我该如何纠正这一点?

+0

您正在使用的AngularJS的版本? –

+1

我刚刚用你的代码创建了一个[plunkr](https://plnkr.co/edit/rtjnZp1UVuyHUtddqiDi?p=preview),它似乎工作正常。 – th1rdey3

回答

0

尝试使用ng-repeat-startng-repeat-end

从角1.2版本起,ng-repeat了名为ng-repeat-startng-repeat-end两个兄妹指令。有了这些,我们可以明确指定ng-repeat的开始和结束。因此,我们可以在任何两个DOM元素上指定ng-repeat-startng-repeat-end,而不是在单个DOM元素上使用ng-repeat指令。

<div class="incident"> 
    <header ng-repeat-start="category in incidentCats" class="category"> 
    <strong>{{ category.name}}</strong> 
    </header> 
    <section ng-repeat-end> 
    <div ng-repeat="incident in category.incidents"> 
     {{ incident.location }}<br> 
     {{ incident.dateTime }}<br> 
     {{ incident.currStatus }}<br> 
    </div> 
    </section> 
</div> 
0

我试图复制的行为,我所看到的一切运作良好。 ng-repeat正在生成HTML结构。这可能与您发布的数据有关。如果发布的数据是正确的,那么HTML应该按预期工作。您可以尝试共享您的确切代码以调试问题。我用下面的数组再现相同的:

$scope.incidentCats = [{ 
    name: "FIRE", 
    incidents: [{ 
    location: "location 1", 
    dateTime: "datetime 1", 
    currStatus: "currStatus 1" 
    }, 
    { 
    location: "location 2", 
    dateTime: "datetime 2", 
    currStatus: "currStatus 2" 
    }] 
}, 
{ 
    name: "CODE BLUE", 
    incidents: [{ 
    location: "location 3", 
    dateTime: "datetime 3", 
    currStatus: "currStatus 3" 
    }] 
}]; 

Plnkr Link