reusable conditionals in angular
Most often, I did end up using stupid conditionals in my angular templates like:
ng-show="user.roles.indexOf('admin') !== -1"
so I decided to move functions to controllers to end up with:
ng-show="isAdmin()"
But then I had some duplication in my controllers which could lead to services but I was not convinced it was a nice way to proceed.
I could have created js objects out of my JSON but I dont like this approach.
I've realized an alternate neat way to do this is to use filters:
ng-show="user | user:'isAdmin'"
I've a working plunkr here
Written by Benjamin Roth
Related protips
3 Responses
Great post! I have never seen a filter used in that way before. I am going to throw my 2 cents in, hopefully it helps people see the other side of the fence.
I feel like that kind of logic should be held in a service. Filters are used mainly for processing and outputting readable data if I am not mistaken. I feel like if you need to do anything more complicated than checking if a variable is truthy, it should be built into a service .
I would build service to handle the logic portion, while exposing just a boolean in your $scope.
app.service('adminViewService', function(user){
// This service only exists to process data before exposing it to the controller.
// All logic would be here, making the controllers very small, just being service calls.
var test = this;
test.isAdmin = {
lastChecked: DateTime,
data: Boolean
}
test.checkIfAdmin = function(){
test.isAdmin.lastChecked = Date.now();
if(user.roles.indexOf('admin') !== -1){
test.isAdmin.data = true;
}else{
test.isAdmin.data = false;
}
}
})
I could very well be wrong though, what do you think?
Services are the most common way to proceed. Actually I generally create a service then use the service in my filter.
Using filters spares a lot of:
- inject service
- attach to controller
- call method in view
I've never seen anyone using filters this way either but I'd recomment it: it feels natural
Actually I'm working on videos for egghead.io maybe it would be published there.
I will have to give it a try :) I am always down for finding ways to make my code more natural and readable.
Now that I am taking a look at it, I can see myself knowing exactly what is going on. In that sense, it is very nice. Though, I would love to see this in action with a ton of elements. Since filters are only called their input changes, I bet it would be just as fast as a controller function.
Brain food :P
Good job man. I would give you another like if could :P