2016-04-23 60 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