1

I've found a bizarre quirk in AngularJS/Firefox where the selectors use grab different elements. I've put it in a Plunker to demonstrate it's effect:

http://plnkr.co/edit/H7stCpQE59i0aUlQ865j?p=preview

Open it in Chrome and click the button. You're actually selecting a hidden <input> element, then Angular passes it's event/parent along, grabs the parent <button> and adds the class .active to it, like so:

$scope.selectTag = function($event){
        var elem = angular.element($event.srcElement).parent();
        if(elem.hasClass('active')){
            elem.removeClass( "active" );
        }else{
            elem.addClass('active');
        }   
    }

In Firefox, though, it selects the <input> element and adds .active to that rather than the <button> that is its parent.

Any ideas on why this is happening?

JVG
  • 20,198
  • 47
  • 132
  • 210
  • 1
    Probably you should use `target` instead of `srcElement` like `var elem = angular.element($event.target).parent();` – Arun P Johny Dec 13 '13 at 00:46
  • See http://stackoverflow.com/questions/5301643/how-can-i-make-event-srcelement-work-in-firefox-and-what-does-it-mean for a description of $event.srcElement – urban_raccoons Dec 13 '13 at 00:50

2 Answers2

3

No need for using jQuery. Just use ng-class. Following requires zero code in controller to accomplish what your code will end up doing. Also controllers shouldn't have any DOM manipulation code in them

<label class="btn btn-default" ng-class="{active:btn_active}" >
  <input class="" ng-click="btn_active=!btn_active" type="checkbox" />
    Button Text
</label>

Learn to look for angular approaches first before using jQuery methodology!

DEMO

charlietfl
  • 170,828
  • 13
  • 121
  • 150
2

As in the comment by Arun P Johny, use $event.target rather than srcElement. But, you shouldn't be manipulating the DOM like that when using Angular JS. Instead, you could do this with ng-class.

<label class="btn btn-default" ng-class="foo">
  <input class="" ng-click="foo=(foo==='active') ? '' : 'active'" type="checkbox" />
    Button Text
</label>
m59
  • 43,214
  • 14
  • 119
  • 136
  • I'll mark this correct as it was first / answered the main issue. Cheers mate! – JVG Dec 13 '13 at 01:53
  • @Jascination Nice, thanks! For anyone that sees this, do also see charlietfl's answer! – m59 Dec 13 '13 at 02:22