4

I'm new to web dev and AngularJS. I'm trying to use the directive ng-if to only display a div block if a list returned from the database is greater than 1, but it's not working. Am I misusing the directive? I've looked around and haven't found any solutions that work. Currently, both divs are displayed and the ng-ifs are ignored.

<div>
    <div ng-if="listOfThings.length > 1">
        <h1> {{listOfThings.length}} </h1>
        </br>
        <div ng-repeat="thing in listOfThings">
           <label> {{ thing.name }} </label>
        </div>
    </div>
    <div ng-if="listOfThings.length == 1" class="col-sm-4 col-sm-offset-4">
        <h1> {{ listOfThings[0].name }} </h1>
        <iframe width="560" height="315" ng-src="{{ listOfThings[0].embed }}" frameborder="0" allowfullscreen></iframe>
    </div>
</div>

I tried this code, which works in Plunker, but not in my code for some reason. In my code, only ng-app works, but ng-if still does not.

    <div ng-app="ngAnimate">
        Click me: <input type="text" ng-model="check" ng-init="check='show'" /><br/>
        Show when check: {{check}}
        <input ng-if="check!='hide'" class="animate-if" placeholder="type the word 'hide'"/>
    </div>
Soubriquet
  • 3,100
  • 10
  • 37
  • 52

2 Answers2

8

What you want instead of this ng-if="{{listOfThings.length}} > 1" is this:

 ng-if="listOfThings.length>1"

ng-if will evaluate the expression.

Check this Online Demo

Dalorzo
  • 19,834
  • 7
  • 55
  • 102
  • I tried your suggestion and it still displays both divs. – Soubriquet May 29 '14 at 17:32
  • @Soubriquet there is plunker demo and it works how about you showing me your code – Dalorzo May 29 '14 at 17:43
  • Ok, so I copied the plunker code you linked into my html and the ng-if still does not work, but the np-app works. :/ I edited my original post to show the plunker code I tried. – Soubriquet May 29 '14 at 18:17
  • Never mind. Thanks for all the help. After looking at the Plunker code, I realized that I downloaded AngularJS 1.3.0 and I was loading in an older version. Thanks again. It works now. – Soubriquet May 29 '14 at 18:25
0

This should do

<div>
    <div ng-if="listOfThings.length > 1">
        <h1> {{listOfThings.length}} </h1>
        </br>
        <div ng-repeat="thing in listOfThings">
           <label> {{ thing.name }} </label>
        </div>
    </div>
    <div ng-if="listOfThings.length == 1" class="col-sm-4 col-sm-offset-4">
        <h1> {{ listOfThings[0].name }} </h1>
        <iframe width="560" height="315" ng-src="{{listOfThings[0].embed}}" frameborder="0" allowfullscreen></iframe>
    </div>
</div>
Mathews
  • 909
  • 1
  • 7
  • 13
  • 1
    @Matthews, can you please explain how this add up to consider this is NOT a copy of the answer already posted? – Dalorzo May 29 '14 at 15:55