1

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.

3 Answers 3

3

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>
Sign up to request clarification or add additional context in comments.

1 Comment

doing it in template much more cleaner and asy way to do it... but if you need that array in controller that is another thing...
1

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:

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.