Search code examples
angularjsangular-ng-if

Angular: ng-if doesn't work, and throws errors


I have results.name getting returned in the data object I'm using. When I print it out, or not use the ng-if, template works fine. However, I don't have this data coming in always, so added a check to not add DOM/HTML when it's not coming in.

This is just a string of data returned, so was assuming this does the null check.

    <h1 ng-if="{{results.name}}" class="name">{{results.name}}</h1>

If I remove ng-if, it works fine.

    <h1 class="name">{{results.name}}</h1>

<!-- ngIf: {{results.name}} -->
Error: [$parse:syntax] http://errors.angularjs.org/undefined/$parse/syntax?p0=results.name&p1=is%20unexpected%2C%20expecting%20%5B%3A%5D&p2=3&p3=%7B%7Bresults.name%7D%7D&p4=results.name%7D%7D
    at Error (native)

Solution

  • You need to change from

     <h1 ng-if="{{results.name}}" class="name">{{results.name}}</h1>
    

    to

     <h1 ng-if="results.name" class="name">{{results.name}}</h1>