Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change class on ng-focus in angularJS

Tags:

angularjs

I have the following html:

<div class="icon fluid select" ng-init="focused = false">
   <i  ng-class="{'large svg guests icon':rooms==2, 'large svg guest icon':rooms==1,'active':focused==true}"></i>
    <label ng-click="closeCalendar();">
   <select ng-model="rooms" name="rooms"   class="fluid" name="rooms" focus-parent selecter required>
     <option value="1" ng-focus="focused = true">Einzelzimmer</option>
     <option value="2" ng-focus="focused = true">Doppelzimmer</option>
    </select>
 </label>

I initialized a model focused with initial value false, I want to change the value of this when an option of a select box is focused or when the selectbox is focused, I tried the above but it didnt work, how can I solve it, is that possible?

like image 927
Avraam Mavridis Avatar asked Dec 11 '22 05:12

Avraam Mavridis


2 Answers

<option> elements cannot receive focus, only the <select> element can.
So you need to put the listeners on the <select> (don't forget to put a blur listener for setting focused back to false):

<select ng-model="rooms" 
        ng-focus="focused=true" 
        ng-blur="focused=false">

See, also, this short demo.

like image 125
gkalpak Avatar answered Jan 02 '23 22:01

gkalpak


I think the issue here is that you seem to be trying to use blur and focus instead of using the binding that is built into angular. So, what you are looking for is basically something like the following:

<i class="icon"  ng-class="{'gbp':rooms=='2', 'usd':rooms=='1'}"></i>
<select ng-model="rooms" name="rooms" class="fluid">
 <option value="1">Dollars</option>
 <option value="2">Pounds</option>
</select>

I changed the variable names, classes and icons to make it make sense with some icons I could find easily but the point is the same. Having ng-model on the select means that as soon as the selected value changes the class will change between "usd" and "gbp" (depending on what they have selected). The rest is just straight forward CSS to show the correct icon.

SEE THE PLUNKER: http://plnkr.co/edit/6cgHFirI2jxXIAGJ83YW?p=preview


EDIT

In order to change the class of an entire div based on the focus and blur you can use the ng-focus and ng-blur on the select much like the following:

<select ng-model="rooms" name="rooms" class="fluid"
        ng-focus="highlight=true" ng-blur="highlight=false">

Both ng-focus and ng-blur will automatically run an apply on the scope which will therefore allow you to change the class with a simple ng-class directive. Take the following as an example:

<div ng-class="{'highlight':highlight==true,'normal':highlight==false}">

You can see these updates to the original plunker here: http://plnkr.co/edit/6cgHFirI2jxXIAGJ83YW?p=preview

Best of luck!

like image 29
drew_w Avatar answered Jan 02 '23 22:01

drew_w