I'm trying to use ng-if
to show certain rows if the condition is met, but can't quite seem to get it to work 100% correctly.
<div style="margin-bottom: 1em;">
<h4><!-- content omitted for brevity--></h4>
<p>
<strong>Covered:</strong>
<a ng-href class="pointer" data-ng-repeat="life in data.list2 track by $index" ng-if="life.beneficiary.length > 0" ng-click="c.editBeneficiary(life)">
<!-- content omitted for brevity-->
</a>
<a ng-href class="pointer" ng-if="life.beneficiary.length = 0" ng-click="c.addBeneficiary()">Add Beneficiary <i class="fa fa-plus-circle" style="color: green;"/></a></p>
</div>
In the above code, if the number of beneficiaries is greater than 0 (ng-if="life.beneficiary.length > 0"
), I want to list out the names and allow the user to edit them if necessary. This part is working fine. However, if the number of beneficiaries equals 0, then I want to have a link that says "Add Beneficiary", and allow the user to do so.
I put the ng-if
statements in the <a>
tag, which I'm not sure is right. When I log in with a user who does NOT have a beneficiary, the "Add Beneficiary" link doesn't show up.
The problem is life.beneficiary.length = 0
is NOT a comparison, it's trying to assign 0
(zero) value to life.beneficiary.length
(which is wrong).
Besides, when there is not beneficiaries life.beneficiary.length == 0
(which is correct) might be falsy because life.beneficiary
could be null
or undefined
(it depends on your controller logic)... but, in order to solve this try:
Change ng-if="life.beneficiary.length = 0"
to ng-if="!life.beneficiary.length"
(this is equivalent to ng-if="life.beneficiary.length == 0"
, but it won't fail in your logic if life.beneficiary
is null
or undefined
)
<a ng-href class="pointer" ng-if="!life.beneficiary.length" ng-click="c.addBeneficiary()">Add Beneficiary
</a>
Also, it is recommended to wrap both links (<a>
) inside an element (span
, div
, ... as you wish) which will contain the ng-repeat
, something like this:
<p>
<!-- there is content omitted for brevity -->
<span data-ng-repeat="life in data.list2 track by $index">
<a class="pointer" ng-if="life.beneficiary.length > 0" ng-click="c.editBeneficiary(life)">
<!-- content omitted for brevity-->
</a>
<a class="pointer" ng-if="!life.beneficiary.length" ng-click="c.addBeneficiary()">Add Beneficiary </a>
</span>
</p>