Reputation: 399
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.
Upvotes: 4
Views: 162
Reputation: 22605
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.
Upvotes: 1
Reputation: 662
If you are going to use this check in only one place of your code, i'd say it doesn't matter except if you want your HTML to look cleaner. It's just a matter of preference.
Using a function on the other hand is better if you are going to check that condition several times in your code.
Upvotes: 5