2016-04-23 43 views
1

我使用角度和離子從服務器加載JSON文件。離子警報 - 檢查結果是否未定義

這是我的代碼:

$scope.showAlert = function(mo,di,mi,don,fr,sa,so) { 
       $ionicPopup.alert({ 
       title: 'Success', 
       content: mo + "<br>" + di + "<br>" + mi + "<br>" + don + "<br>" + fr + "<br>" + sa+ "<br>" + so 
       }).then(function(res) { 
       console.log('Test Alert Box'); 
       }); 
      }; 

對於檔案:

<i class="icon ion-ios-clock-outline links" ng-click="showAlert(item.openingHours[0], item.openingHours[1], item.openingHours[2], item.openingHours[3], 
    item.openingHours[4], item.openingHours[5], item.openingHours[6] 
)"></i> 

我的問題是,有時結果,例如item.openingHours [6]是未定義的。我不想在我的警報中出現未定義的文字。如何檢查警報中的值是否未定義?

回答

2

使用條件(三元)運算符?,檢查str定義,如果定義的br返回值,如果不是 - 空字符串:

$scope.showAlert = function(mo, di, mi, don, fr, sa, so) { 
    function getStrWithBr(str) { 
    return str ? str + '<br/>' : ''; 
    } 
    var content = 
    getStrWithBr(mo) + 
    getStrWithBr(di) + 
    getStrWithBr(mi) + 
    getStrWithBr(fr) + 
    getStrWithBr(sa) + 
    so || ''; 
... 
+0

固定的,現在'br'加入只有當值被定義。 – alexmac

+0

非常感謝@亞歷山大! – olivier