Summer Developer
Summer Developer

Reputation: 2086

Angular Ng-If Appears To Lag

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.

Upvotes: 1

Views: 1134

Answers (2)

Jayant Patil
Jayant Patil

Reputation: 1587

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

Upvotes: 0

Kishor Sharma
Kishor Sharma

Reputation: 599

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.

Upvotes: 2

Related Questions