当没有数据时,防止ng-repeat显示图像

时间:2017-07-03 04:58:29

标签: angularjs

在我们的大多数角度页面上,我们遇到了这个恼人的错误,我们似乎无法找到解决方案。

GET http://localhost:8080/img/flagNations/%7B%7B%20bookings.language%20%7D%7D.png 404 (Not Found)

代码没问题,只有在ng-repeat中没有数据时才会出现错误。

vm.checkinTodayShowAll = false;

if (res.checkinToday.length) {
  vm.checkinTodayShowAll = true;
  vm.checkinToday = res.checkinToday; 
}

在页面上,如果没有数据,我甚至会隐藏它......

<table class="start-table start-checkin-table" ng-show="vm.checkinTodayShowAll">

但它仍然希望渲染该图像

<tr ng-repeat="bookings in vm.checkinToday" class="start-text">
  <td class="start-left start-border overflow">
    <img src="./img/flagNations/{{ bookings.language }}.png" class="start-flag">
  </td>
</tr>

ng-repeat没有任何内容时,我们如何阻止它尝试渲染图像?

4 个答案:

答案 0 :(得分:3)

使用ng-if代替ng-show

<table class="start-table start-checkin-table" ng-if="vm.checkinTodayShowAll.length>0">

而不是:

<table class="start-table start-checkin-table" ng-show="vm.checkinTodayShowAll">
  

ng-show:只是隐藏视图它仍在DOM中。
ng-if:删除   来自DOM的元素

答案 1 :(得分:2)

使用ng-if代替ng-show

<table class="start-table start-checkin-table"  ng-if="vm.checkinTodayShowAll.length > 0">
 <tr ng-repeat="bookings in vm.checkinToday" class="start-text">
    <td class="start-left start-border overflow">
        <img src="./img/flagNations/{{ bookings.language }}.png" class="start-flag">
    </td>
 </tr>

答案 2 :(得分:2)

使用ng-if

<tr ng-repeat="bookings in vm.checkinToday" class="start-text">
    <td class="start-left start-border overflow">
        <img src="./img/flagNations/{{ bookings.language }}.png" ng-if="vm.checkinToday.length > 0" class="start-flag">
    </td>
 </tr>

答案 3 :(得分:1)

//Try this one and it will boost performance also
<table class="start-table start-checkin-table" ng-if="vm.checkinTodayShowAll.length">  
<tr ng-repeat="bookings in vm.checkinToday track by $index" class="start-text">
<td class="start-left start-border overflow">
    <img src="./img/flagNations/{{ bookings.language }}.png" class="starflag">
</td>