2014-07-18 20 views
0
if (typeof $scope.input.gps === 'undefined') { 
    $scope.msgBody = 'Location not found.'; 
} else { 
    $scope.msgBody = $scope.input.gps+' not found.'; 
} 
flash.pop({title: 'Error', body: $scope.msgBody, type: 'error'}); 

會不會有if語句來做到這一點更簡單的方法,包括它的flash.pop簡化的Javascript的if語句未定義

+0

爲什麼?你對「更容易」的定義是什麼? – RobG

回答

4

即使最初輸入幾個字符,清晰,易於維護的代碼也沒有問題,它可能會在以後節省大量時間和精力。

似乎你需要設置$ scope.msgBody的值,我認爲在作業中這樣做不是一個好主意。考慮:

$scope.msgBody = typeof $scope.input.gps === 'undefined'? 'Location not found.' : 
                  $scope.input.gps + ' not found.' 

但是,我不認爲這是「更容易」。

3

中您可以使用$scope.msgBody = ($scope.input.gps || 'Location') + ' not found.';

但請注意,Location將用於不僅當$scope.input.gpsundefined,而且如果null""0NaNfalse。這些值由falsy概念覆蓋,請參閱http://www.sitepoint.com/javascript-truthy-falsy/