ngIf始终评估为true

时间:2015-04-07 20:00:50

标签: javascript angularjs nw.js

我正在使用v1.3.9开发AngularJS应用程序。我有几个ng-if指令总是评估为真,我无法弄清楚原因。

<tr data-ng-repeat="line in chat">
                    <td class="message-timestamp">{{line.time | date:'short'}}</td>
                    <div ng-if="line.type === 'gist'">
                        <td class="message-nick">{{line.nick}}</td>
                        <td class="message-text">{{line.message}}
                            <p>
                                <code ng-show="showGist" walrus-auto-gistify data-gist-id="{{line.options[0]}}"></code>
                                <br>
                                <button ng-click="showGist = !showGist" class="btn btn-primary btn-xs">Show/Hide</button>
                            </p>
                        </td>
                    </div>
                    <div ng-if="false">
                        <td class="message-nick"><span class="glyphicon glyphicon-arrow-right"></span></td>
                        <td class="message-text">{{line.message}}</td>
                    </div>
                </tr>

当我运行它时,两个ng-if指令都被评估为true,因此显示两个div

chat只是一个对象数组。

1 个答案:

答案 0 :(得分:4)

我很确定这与<div>作为<tr>的直接子女的事实有关。我过去曾遇到过这类设计的问题,导致奇怪的行为。

解决方案是将<div>放在<td>内,如下所示:

<tr data-ng-repeat="line in chat">
    <td class="message-timestamp">{{line.time | date:'short'}}</td>
    <td class="message-nick">
        <div ng-if="line.type === 'gist'">{{line.nick}}</div>
        <div ng-if="line.type !== 'gist'"><span class="glyphicon glyphicon-arrow-right"></span></div>
    </td>
    <td class="message-text">
        <div ng-if="line.type === 'gist'">
            <p>
                <code ng-show="showGist" walrus-auto-gistify data-gist-id="{{line.options[0]}}"></code>
                <br />
                <button ng-click="showGist = !showGist" class="btn btn-primary btn-xs">Show/Hide</button>
            </p>
        </div>
        <div ng-if="line.type !== 'gist'">{line.message}}</div>
    </td>
</tr>

编辑:尝试使用JSFiddle here