I have a simple ng-repeat:

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

I am trying to only display records if a bool value is true:

My controller:

$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();
}

However nothing is displayed on the front end.

有帮助吗?

解决方案 2

You are pusing the item.visited versus item. You need to update your push and indexOf statements. (see the last part of my answer because filter is better in your situation)

Change:

 groupArrayNew.push(item.visited)

To

 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();
}

You could also bypass the function and use the built in filter:

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

Sample plnkr that shows both:

其他提示

Or do it in the template:

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

or (as suggested in the comments) use a filter:

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

Something like

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

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

    return groupArrayNew;
}

Although has been pointed out in the comments, unless you need groupArrayNew for other purposes (which I don't suspect you do as it is calculated each time by the function), you can achieve what you want with a filter

<li ng-repeat="country in countries | filter:{visited:true}">
    {{country.name}}
</li>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top