Question

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.

Was it helpful?

Solution 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:

OTHER TIPS

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top