I want to check boolean data with angular ng-switch
this is my code. but it is not working
<div ng-switch={{Item.ItemDetails.IsNew}}>
<div ng-switch-when="true">
<p class="new fontsize9 fontWeightBold">NEW</p>
</div>
</div>
<div ng-switch={{Item.ItemDetails.IsFeatured}}>
<div ng-switch-when="true">
<div class="featured">
<p class="fontWeightBold fontsize8">featured</p>
</div>
</div>
</div>
values of {{Item.ItemDetails.IsNew}} and {{Item.ItemDetails.IsFeatured}} are true or false
NgSwitchCaselinkProvides a switch case expression to match against an enclosing ngSwitch expression. When the expressions match, the given NgSwitchCase template is rendered. If multiple match expressions match the switch expression value, all of them are displayed.
With NgIf we can conditionally add or remove an element from the DOM . If we are faced with multiple conditions a cleaner alternative to multiple nested NgIf statements is the NgSwitch series of directives.
Definition and Usage The ng-switch directive lets you hide/show HTML elements depending on an expression. Child elements with the ng-switch-when directive will be displayed if it gets a match, otherwise the element, and its children will be removed.
The important difference between the ngIf solution is that through NgSwitch we evaluate the expression only once and then select the element to display depending on the result. Using ngIf we can conditionally add or remove an element from the DOM.
Convert the boolean to a string:
<div ng-switch="Item.ItemDetails.IsNew.toString()">
<div ng-switch-when="true">
If you are just checking for true values, ng-if seems more appropriate and reduces the need for additional divs containing the code, reducing your sample too:
<div ng-if="Item.ItemDetails.IsNew">
<p class="new fontsize9 fontWeightBold">NEW</p>
</div>
<div class="featured" ng-if="Item.ItemDetails.IsFeatured">
<p class="fontWeightBold fontsize8">featured</p>
</div>
Full docs at: http://docs.angularjs.org/api/ng.directive:ngIf
This syntax works for me:
<div ng-switch="Item.ItemDetails.IsFeatured">
<div ng-switch-when="true">FEATURED ITEM HTML</div>
<div ng-switch-default>REGULAR ITEM HTML (not featured)</div>
</div>
You should remove the {{}} from the ng-switch:
Change this <div ng-switch={{Item.ItemDetails.IsNew}}>
to <div ng-switch=Item.ItemDetails.IsNew>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With