13

I'm having trouble finding an elegant solution to Enums and especially searching in Enums with AngularJS.

Let me describe a situation and how I handled it: Say I have an object called Event This event has 2 properties : Severity and Status. Both of which are Enums, defined by ID (1, 2,3) and Title (for Severity : "Light", "Normal", "Important" and for Status : "Open", "Closed", "Pending Approval")

The Event objects that come from the Service have the ID's of the Enums, and when I want to display the object I bind with {{ severityIdToTitle(Event.Severity) }} SeverityIdtoTitle is a method on my controller which calls a method on my service which returns the value of the Enum based on the id recieved The problem arises when I want the user to be able to search the object through text, the AngularJS filter doesn't know the actual "string" value of the Enum, and so I reach my problem.

I know many workarounds around this, and have a few options, but I wonder what would be anelegant and clean solution to this? Did what I do complicate things and there's a better way?

Thanks guys!

Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
Shushan
  • 1,235
  • 1
  • 10
  • 15
  • hard to answer without more specific use case for `search`, seeing how service works etc. Also since you have workaround ideas...should be providing those. Help received on this site is based on troubleshooting live code. Will get a lot more help by creating a demo in plunker or jsfiddle.net that gives overview of issue also. – charlietfl Nov 23 '13 at 17:36
  • Why are you not doing an enum in Javascript and then just using it in Angular? I found this question: http://stackoverflow.com/questions/287903/enums-in-javascript useful. I implemented Duncan's solution. – Rob Feb 22 '14 at 22:39

1 Answers1

5

Interesting question. I would create a custom filter instead of using the severityIdToTitle function. Filters are designed for formatting data to present to the user, so converting an id to a string is a good use case for one. The filter should depend on a service that knows the two-way mapping between the enum identifiers and their values. As for how to do that mapping, that is a general JavaScript question. There is one good thread about this here.

Community
  • 1
  • 1
jelinson
  • 845
  • 8
  • 15
  • Nice, ill go with the filter for showing the title, yet how do l go about filtering the events(say I have an ng repeat list) by user input when the user enters text and the actual values are numbers? – Shushan Nov 24 '13 at 05:57
  • 1
    You could do something like `ng-repeat=item in items | filter:(user_input|event_name_to_id)`. In other words, you can just nest the filters. If you create a Plnkr or JSFiddle with your starting example, I'll happily code up a complete solution using this. – jelinson Nov 25 '13 at 05:44