init fail init fail - 5 months ago 25
AngularJS Question

What is the "angular" way to perform a conditional ng-if check?

Say I have a string that contains a value of "HOMEPAGE"

vm.string = "HOMEPAGE"


and I want to perform an ng-if inside of a div that causes it to display if vm.string is equal to one of these five strings.

"HOMEPAGE"
"ABOUT"
"STORE"
"EXAMPLE"
"SOMETHING"


I could do this using or operators inside of the ng-if to achieve the desired effect

<div ng-if="WhateverController.string == 'HOMEPAGE'
|| WhateverController.string == 'ABOUT'
|| WhateverController.string == 'STORE'
|| WhateverController.string == 'EXAMPLE'
|| WhateverController.string == 'SOMETHING'">

This will display because the string is 'HOMEPAGE'

</div>


I could also do this by creating a function that returns a boolean in my controller.

vm.isTrue = function () {

return (vm.string == 'HOMEPAGE'
|| vm.string == 'ABOUT'
|| vm.string == 'STORE'
|| vm.string == 'EXAMPLE'
|| vm.string == 'SOMETHING');

};

<div ng-if="WhateverController.isTrue">
This will display because the string is 'HOMEPAGE'
</div>


My question to you all is which of these two methods is considered the more "angular" way? I'm partial to doing this inside of the javascript because it makes the HTML look cleaner, but I am curious as to whether there is one way preferred over the other and why.

Answer

I think second one is better. It's not even Angular way, but way of writing clean code.

You should also avoid writing very long logical conditions and instead split it to several variabled. For example:

vm.age > 5 && vm.age < 100 && vm.name.length > 5 && (vm.location == "Spain" || vm.location == 'England')

You should instead use:

vm.isTrue = function(){
    var isOldEnough = vm.age > 5;
    var isYoungEnough = vm.age < 100;
    var nameLengthIsCorrect = vm.name.length > 5;
    var inSpainOrInEngland = ["Spain","England"].includes(vm.location);
    return isOldEnough && isYoungEnough && nameLengthIsCorrect && inSpainOrEngland;
}

This way your code is self-explanatory.