Jason Jason - 4 months ago 21
AngularJS Question

ng-if to hide all elements in page except 1

I have several divs on my page which use an ng-if to show. My issue is that certain elements are duplicates.

What I would like to do is use another expression in the ng-if for this example i added below (hideMultiplePost) to hide these duplicate elements and my idea is to identify them by adding a class which uses the post id since the duplicate elements share the same id.

<div ng-repeat="post in postList">
<div class="{{post.id}}" ng-if="post.cat.length > 0 && hideMultiplePost(post.id)">
</div>

<div ng-repeat="post in postListV2">
<div class="{{post.id}}" ng-if="post.cat.length > 0 && hideMultiplePost(post.id)">
</div>


Can someone put me in the right direction in using an expression (hideMultiplePost) where I check for duplicate classes and exclude them from the frontend but leave one them as I don't want to exclude them all.

Answer

If you cannot control the data in, then you can remove dupes using a filter. I have assumed it's an ng-repeat, but you can edit for your own use. More detail in fiddle.

   <div ng-repeat="item in data | dedupe:'id'">
      {{item.id}}: {{item.name}}
   </div>

Edit: Concat the two sources (postList and postListV2) in your controller, and then use the filter to dedupe:

function MyCtrl($scope) {
    $scope.postList = postList;
    $scope.data = $scope.postList.concat(postListV2)
}

More info in the fiddle: http://jsfiddle.net/Lvc0u55v/7736/