1

I am using an ng-if on an element to hide it until a certain condition is met. However, the condition gets met in my controller but the element appears to still not be in the DOM when my jquery selector tries to find it. It appears to be lagging perhaps, or maybe I am doing something wrong.

My HTML:

<div ng-if="!aBreadNotSelected" ng-click="goBack()" id="goBack"><i class="fa fa-arrow-left"></i> <span id="goBackText">Go <u>Back</u> To Menu</span></div>

My Controller:

$scope.myFunc = function(){
$scope.aBreadNotSelected = false;
$("#goBack").css("left","0px");
}

myFunc fires, I know it does because the rest of it which I excluded here gets executed. But jquery can't find $("#goBack") even though it looks for it after aBreadNotSelected goes to false, which should satisfy the ng-if, so what is happening do you think?

:(

Edit: I know the jquery is fine because when I type $("#goBack").css("left","0px"); in the console after myFunc fires, I get what I want.

Summer Developer
  • 2,056
  • 7
  • 31
  • 68
  • Read this first: [“Thinking in AngularJS” if I have a jQuery background?](http://stackoverflow.com/a/15012542/968155) before doing anything else. It will save you a lot of headache – New Dev Sep 14 '15 at 04:45
  • 1
    You should not write any jQuery code in controller. It needs to be handled in directive. Moreover, You can use ng-class through which you can handle this CSS properties. Check this out http://stackoverflow.com/questions/16529825/angularjs-ngclass-conditional – Alpesh Prajapati Sep 14 '15 at 04:55

2 Answers2

2

As per Doc:

The ngIf directive removes or recreates a portion of the DOM tree based on an {expression}.If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.

This means you html DOM needs to be rendered again.

In addition to this as your HTML DOM is not present jQuery binding will not work as expected. You either need to use .on(handler, func) to get desired event to be triggered.

You can try to use ng-show instead.

Kishor Sharma
  • 599
  • 8
  • 15
0

You have to initialize you variable then only it will work as you want see here http://jsfiddle.net/a8Loxpku/

$scope.aBreadNotSelected = true;
$scope.myFunc = function(){
$scope.aBreadNotSelected = false;
$("#goBack").css("left","0px");
}

Hope this help you

Jayant Patil
  • 1,537
  • 2
  • 11
  • 18