sova sova - 2 months ago 6
AngularJS Question

angular conditionally show div in nested ng-repeat

<div class="sunti_contain" ng-repeat="sunti in suntis track by $index">
<div class="individual_sunti" ng-click="update_ancestor(sunti)">
<!--needs a unique div#id via angularz-->
<div class="sunti_content" ng-bind="sunti.content"></div>
<div class="sunti_tags" ng-bind="sunti.tags"></div>
<div class="sunti_author" ng-bind="sunti.author"></div>
<div class="sunti_shortid" ng-bind="sunti.short_id"></div>
<div class="sunti_ancestor" ng-bind="sunti.ancestor"></div>
</div>
<div class="sunti_reply_carriage_wrapper">
<div class="sunti_reply_carriage" ng-show="!sunti.descendents.length">
<div class="individual_sunti reply_carriage_sunti" ng-repeat="descendent in sunti.descendents">
<div class="sunti_content" ng-bind="descendent.content"></div>
<div class="sunti_tags" ng-bind="descendent.tags"></div>
<div class="sunti_author" ng-bind="descendent.author"></div>
<div class="sunti_shortid" ng-bind="descendent.short_id"></div>
</div>
</div>
</div>
</div>


I want to only show the div.sunti_reply_carriage if there are any descendents rendered in the ng-repeat. If there are no descendents, I don't want the div sunti_reply_carriage to appear at all. However, the
ng-show="!sunti.descendents.length"
does not work, presumably because it's just outside/before the ng-repeat that references
descendents in sunti.descendents


How can I do this?

Answer
ng-show="!sunti.descendents.length"

Above code does not show the following code block if length is greater than zero

Ex: If sunti.descendents.length is 1 then !1 is false then ng-show="false"

If sunti.descendents.length is 0 then !0 is true then ng-show="true"

So, change the expression to ng-show="sunti.descendents.length"

You can use ng-if as well if you want to completely remove the code block from DOM if the expression evaluates to false.

  <div class="sunti_reply_carriage" ng-show="!sunti.descendents.length">
                        <div class="individual_sunti reply_carriage_sunti" ng-repeat="descendent in sunti.descendents">
                            <div class="sunti_content" ng-bind="descendent.content"></div>
                            <div class="sunti_tags" ng-bind="descendent.tags"></div>
                            <div class="sunti_author" ng-bind="descendent.author"></div>
                            <div class="sunti_shortid" ng-bind="descendent.short_id"></div>
                        </div>
                    </div>
Comments