Search code examples
javascriptangularjsangular-ng-if

a ng-if with 3 condition doesn't work? angularjs


I tried to have 3 conditions in the same ng-if and my app stopped scrolling.... I separated the 3 conditions in 2 divs, 2 conditions first div, and 1 condition in the second div and now it works... but I dont understand why...

params.schedule value is undefined-undefined-

<div class="inputs-row" ng-if="params.schedule.length > 0 && params.schedule != undefined">
                        <div ng-if="params.schedule != 'undefined-undefined-'">
                            <div class="inputCol">
                                {{'ScheduleDate' | translate}}
                            </div>
                            <div class="inputCol">
                                {{params.schedule}}
                            </div>
                        </div>
                    </div>

Can anyone validate this or explan it?


Solution

  • You need to change the order of your logic so that the thing that is most likely to fail comes first. You can also use implied "truthiness" to simplify this logic

    ng-if="params.schedule && params.schedule.length && params.schedule != 'undefined-undefined-'"
    

    If params.schedule is false (undefined), it stops there. All good.

    If you check params.schedule.length FIRST and params.schedule is undefined, it will error out because you're checking for a property of something that is undefined.

    If if(params.schedule.length > 0) is the same this as if(params.schedule.length) because any non-zero length = true.

    Here's a good primer on using truthiness: https://codeburst.io/javascript-null-vs-undefined-20f955215a2