Gonzalo Diaz Ailan
Gonzalo Diaz Ailan

Reputation: 722

ng-if="true" + data-ng-if="true" evaluates to false?

The fact is that if you use ng-if="truthyValue" and data-ng-if="truthyValue" inside an html element using angularJS +1.6, the affected element won't render in the DOM. This is true even if you use ng-if and data-ng-if with the boolean true.


Does anybody knows why does this happen ?

Upvotes: 3

Views: 5356

Answers (2)

Nick is tired
Nick is tired

Reputation: 7055

This answer takes multiple quotes of AngularJS's directive documentation.


The reason for this is that AngularJS HTML templates are compiled:

For AngularJS, "compilation" means attaching directives to the HTML to make it interactive.

During compilation, template directives undergo a process called Normalization which involves changing HTMLs case-insensitive names to the camelCase names used in AngularJS, this follows the following process:

  1. Strip x- and data- from the front of the element/attributes.
  2. Convert the :, -, or _-delimited name to camelCase.

After this process you can see that you'll have two ngIf directives attached to the same HTML element, these then interfere (the reason it works for two occurrences of ng-if but not an ng-if and an data-ng-if is that your web browser discards one of the ng-ifs if there are two rather than them both reaching the AngularJS compiler).


Thus the solution for this not to occur is don't use multiple directives in your HTML which AngularJS normalizes to the same thing.

Upvotes: 3

Dimitrios Matanis
Dimitrios Matanis

Reputation: 926

So after experimenting with this, it looks like it's working just fine, using Angular 1.6.5

You are not supposed to use both data-ng-if and ng-if on the same element anyway. Stick with one of them.

<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    <div ng-if="false">hello there</div>
    <div ng-if="true">whats up</div>
  </div>
</div>

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {


}]);

Here is a codepen:

https://codepen.io/anon/pen/YxoXgE

This behavior is not only seen in ng-if but also other angular directives such as ng-repeat. Of course, removing one of the declaration fixes the error immediately.

Here is an example that doesn't work, using both ng-repeat and data-ng-repeat: https://codepen.io/anon/pen/KvjdZV

Upvotes: -2

Related Questions