当数组在angularjs中没有要比较的值时,如何指定默认值

时间:2015-03-25 14:45:13

标签: javascript angularjs angularjs-ng-repeat

您好我是angularjs的新手我有以下代码, HTML

//here i have one more ng-repeat so comparing with this home.home_info_id to avgrating avg.home_inof_id
<div ng-repeat=' home in homeDetailInfo'>
    <div ng-repeat="avg in homerating">
      <div ng-if="avg.home_info_id==home.home_info_id">
        <div class="star" ng-modal="avg" data-score="{{avg.avg}}"></div>
      </div>
    </div>

这里我的数据是

hallrating=[
{"home_info_id":"94","avg":"3.33333333333333"},
{"home_info_id":"119","avg":"4"},
{"home_info_id":"95","avg":"4.5"}
]

所以它适用于3个家庭但问题是我有4个家庭,而第四个家庭尚未评级所以我需要显示该家庭的数据得分='0'。 我尝试了如下

<div ng-repeat=' home in homeDetailInfo'>
        <div ng-repeat="avg in homerating">
          <div ng-if="avg.home_info_id==home.home_info_id">
            <div class="star" ng-modal="avg" data-score="{{avg.avg}}"></div>
          </div>
         <div ng-if="avg.home_info_id!=home.home_info_id && avg.avg!=''">
            <div class="star" ng-modal="avg" data-score="0"></div>
          </div>
        </div>

not worked for me i also tried
<div ng-repeat=' home in homeDetailInfo'>
        <div ng-repeat="avg in homerating">
          <div ng-if="avg.home_info_id==home.home_info_id">
            <div class="star" ng-modal="avg" data-score="{{avg.avg}}"></div>
          </div>
         <div ng-if="!avg.avg">
            <div class="star" ng-modal="avg" data-score="0"></div>
          </div>
        </div>

2 个答案:

答案 0 :(得分:1)

您可以创建方法。

$scope.showScore = function(score) {
    if (angular.isDefined(score)) {
        return score;
    } else {
        return 0;
    }
}

然后在html中

<div class="star" ng-modal="avg" data-score="showScore(avg.avg)"></div>

编辑:错过了围绕avg.avg。(/ p>)的()

答案 1 :(得分:0)

<div ng-repeat=' home in homeDetailInfo'>
  <div class="star" data-score="{{ getScore(home.home_info_id) }}"></div>
</div>

然后在你的控制器中

$scope.getScore = function (homeInfoId) {
  var score = 0;

  homerating.forEach(function (rating) {
    if (rating.home_info_id === homeInfoId) {
      score = rating.avg;
    }
  }

  return score;
};