VSO VSO - 10 months ago 64
jQuery Question

jQuery Lite Element Finder with Ng-If on Angular Directive

I have a directive with two html elements, one is an

directive and the other is not:

<div ng-if="true" id="ngIfTest">TEST WITH NG-IF</div>

<div id="withoutNgIfTest">TEST WITHOUT NG-IF</div>

I select the elements like so:

var ngIfElement = angular.element(elem[0].querySelector('#ngIfTest'));
var noNgIfElement = angular.element(elem[0].querySelector('#withoutNgIfTest'));

I am able to select the element that does not use ng-if, but not the one that does.

LIVE EXAMPLE HERE (Click on the text to see it selecting one properly)

var myApp = angular.module('myApp',[]);

myApp.directive('myDirective', function() {
return {
link: function(scope,elem) {

//var myDivElement = elem #myDiv;
var myDivElement = angular.element(elem[0].querySelector('.myDiv'));

elem.bind('click', function() {
console.log('Element clicked');
scope.$apply(function() {
scope.color = "red";


function MyCtrl($scope) {

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-controller="MyCtrl">
<div id="me" style= "background-color:yellow;" my-directive>
<div id="myDiv" class="myDiv">TEST</div>

I realize that this has to do with ng-if creating its own scope, but I am not sure how to get around it.

Related question that I am drawing from: AngularJS: How to .find using jqLite?


It's not really an issue of creating it's own scope, it's because ngIf doesn't write to the DOM when the condition isn't satisfied, so your jQuery selector never finds it. Use ngShow and ngHide if you need the element to exist in the DOM and be queryable.