Angularjs - 如何根据bool值将项目推送到数组中

时间:2014-05-01 11:59:00

标签: angularjs boolean angularjs-scope angularjs-ng-repeat

我有一个简单的ng-repeat:

<li ng-repeat="country in getCountryGroups()">
        {{country.name}}
</li>

如果bool值为true,我只想显示记录:

我的控制器:

$scope.countries = [
    {name: 'France', population: 63.1, visited: true},
    {name: 'Spain', population: 23.5, visited: true},
    {name: 'Greece', population: 44.6, visited: true},
    {name: 'United Kingdom', population: 61.8, visited: false}
];


$scope.getCountryGroups = function () {
    var groupArrayNew = [];

    angular.forEach($scope.countries, function (item, idx) {
        if (groupArrayNew.indexOf(item.visited) == -1)
          groupArrayNew.push(item.visited)
    });

    return groupArrayNew.sort();
}

但前端没有显示任何内容。

3 个答案:

答案 0 :(得分:3)

或者在模板中执行:

<li ng-repeat="country in countries">
  <p ng-show="country.visited">{{country.name}}</p>
</li>

或(如评论中所示)使用filter

<li ng-repeat="country in countries | filter:{visited:true}">
  {{country.name}}
</li>

答案 1 :(得分:1)

您正在点击item.visiteditem。您需要更新pushindexOf语句。 (请参阅我的答案的最后一部分,因为filter在您的情况下更好)

变化:

 groupArrayNew.push(item.visited)

 groupArrayNew.push(item)  

$scope.getCountryGroups = function () {
  var groupArrayNew = [];
  angular.forEach($scope.countries, function (item, idx) {
    if (item.Visited)
      groupArrayNew.push(item)l
  });
  return groupArrayNew.sort();
}

您也可以绕过该功能并使用内置的filter

<li ng-repeat="country in countries|filter:{visited:true}">{{country.name}}</li>

Sample plnkr显示两者:

答案 2 :(得分:0)

这样的东西
$scope.getCountryGroups = function () {
    var groupArrayNew = [];

    angular.forEach($scope.countries, function (item, idx) {
        if (item.visited)
          groupArrayNew.push(item)
    });

    return groupArrayNew;
}

虽然在评论中已经指出,除非你需要groupArrayNew用于其他目的(我不怀疑你这样做,因为每次通过该功能计算),你可以实现你的目标想要一个过滤器

<li ng-repeat="country in countries | filter:{visited:true}">
    {{country.name}}
</li>