Wednesday, February 26, 2014

Sweet Select2's in Angular!

So I had this awesome idea to make my Select2 dropdown much nicer by adding group names to the dropdown.  { Yes, I know, novel idea! }  The problem is... it's Select2.  Which I guess wouldn't be such a big deal, but I'm also binding my dropdown with Angular.  If you're not technical, let me help you out by saying stop reading and move on.

So, this is how I { with the help of a colleague } did it:

<select ui-select2="{allowClear:true}" data-placeholder="Product" class="input-max ProductDropdown" ng-model="ProductID">

<optgroup label="Ranged">

<option ng-repeat="p in Products | filter: { IsRanged: 'true'}" value="{{p.ProductID}}">{{p.ProductName}}</option>

</optgroup>

<optgroup label="No Range">

<option ng-repeat="p in Products | filter: { IsRanged: 'false'}" value="{{p.ProductID}}">{{p.ProductName}}</option>

</optgroup>

</select>
 
 


Well, first it's not perfect.  I could have done this in javascript when I was instantiating the select2, but I chose this route since the form is way more complex.  This select lives in 'n' number of rows, repeated with an Angular directive template.  SO... while the SAME list is getting filtered twice { once for Ranged, once for NonRanged }, it is very fast and very nice looking. 

I'm happy with the result.  It's not the most efficient code written, but it works and enhances the user's experience.  Win-win!

No comments:

Post a Comment