I have a directive with two html elements, one is an ng-if
directive and the other is not:
<div>
<div ng-if="true" id="ngIfTest">TEST WITH NG-IF</div>
</div>
<div>
<div id="withoutNgIfTest">TEST WITHOUT NG-IF</div>
</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() {
elem.css('background-color','red');
myDivElement.css('color','blue');
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>
</div>
</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?