【问题标题】:Angular issue when ng-if is 0ng-if 为 0 时的角度问题
【发布时间】:2017-01-24 04:17:19
【问题描述】:

ng-if="expression value is 0" 无法正常工作时,我遇到了问题。

这里是 plunker 的链接:http://plnkr.co/edit/dILXSIHHzvuv1nhbxdga?p=info

在选择更改时,我使用模型值来显示特定的文本框。

<select ng-model="location.locationSchedule.scheduleType" 
    ng-options="schedule.id as schedule.name for schedule in scheduleTypes track by schedule.id">
   <option value="">Choose a Schedule Type</option>
</select>    

还有输入字段

<input ng-model="location.locationSchedule.frequency" 
    placeholder="Enter Week No." 
    ng-if="location.locationSchedule.scheduleType == 0"/>
<input ng-model="location.locationSchedule.frequency" 
    placeholder="Enter Week No." 
    ng-if="location.locationSchedule.scheduleType == 1"/>

如果location.locationSchedule.scheduleType == 1 它显示特定的文本框,但当它为0 时不显示

【问题讨论】:

    标签: javascript angularjs angular-ng-if


    【解决方案1】:

    那是因为父 ngIf

    替换

    ng-if="location.locationSchedule.scheduleType != ''"
    

    ng-if="location.locationSchedule.scheduleType !== ''"
    

    或者任何更合适的(cf Implied string comparison, 0='', but 1='1'

    【讨论】:

    • 知道了.. !!谢谢。
    • 还有一个问题,我已经将值初始化为2,但仍然没有选择正确的选项,您知道吗? plnkr.co/edit/DmvqkS9SqTfRQQH59p72?p=preview
    • 我会说这是因为它无法以相反的方式进行绑定(当您选择一个选项时,他能够用正确的值填充location.locationSchedule.scheduleType,但是如果您更改模型直接,找不到对应的选项)
    • 例如,如果您使用 $scope.location.locationSchedule.scheduleType = {id: 2}; 初始化模型,您会看到选择了正确的选项(我知道这不是您想要的,因为您希望模型中是整数而不是对象,但这就是 Angular 的工作方式)
    • 谢谢@VaILeNain。
    【解决方案2】:

    改变

    ng-if="location.locationSchedule.scheduleType != ''"
    

    ng-if="location.locationSchedule.scheduleType !== ''"
    

    因为0 == '',两者都是假的,但它们的类型不一样。

    【讨论】:

    【解决方案3】:

    不知道为什么大家都在比较scheduleType !== '' 现在我明白为什么了,为了清楚起见,请在您的问题中包含 div html。

    对于比较0的问题,可以通过严格比较来解决,包括!== ''=== 0

    <div class="form-group days-list" ng-if="location.locationSchedule.scheduleType !== ''">
        <input ng-model="location.locationSchedule.frequency" 
            placeholder="Enter Week No." 
            ng-if="location.locationSchedule.scheduleType === 0"/>
        <input ng-model="location.locationSchedule.frequency" 
            placeholder="Enter Week No." 
            ng-if="location.locationSchedule.scheduleType === 1"/>
    

    http://plnkr.co/edit/JWBz4QlhLDHrNiMo36zI?p=preview

    【讨论】:

    • 还有一个问题,我已经将值初始化为2,但仍然没有选择正确的选项,您知道吗? plnkr.co/edit/DmvqkS9SqTfRQQH59p72?p=preview
    • 在 ng-option 中试试这个 ng-options="schedule.id as schedule.name for schedule in scheduleTypes"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 2022-11-22
    • 2016-04-23
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    相关资源
    最近更新 更多