【问题标题】:Angular select does not update model properly角度选择无法正确更新模型
【发布时间】:2015-09-01 09:55:57
【问题描述】:

在我的 AngularJS 应用程序中,我有一个绑定到模型的 select。 当用户从列表中选择一个选项时,模型不会更新。 当用户再次点击相同的选项时,模型就会更新。

正如您所理解的,这不是理想的行为。在我的测试中,我用<input type='text'> 替换了select,它按预期工作。我的问题是什么?我无法在 JSFiddle 中复制它,所以我会发布我认为相关的尽可能多的代码。

索引.html

这是我为每种类型的可设置属性获得正确的模板。 所以 text-input 得到一个input type='text'frequenty 得到他的模板,一个select

<div ng-repeat="item in propertyList">
    <ng-include src="getTemplate(item, formObject)"></ng-include>
</div>

Controller.coffee

这里返回了正确的模板,并设置了可选择的频率。

$scope.getTemplate = (prop, object) =>  
   if $builder.widgets.hasOwnProperty prop #Here it found the frequency dropdown template.
     return $builder.widgets[prop]               
   else if angular.isString propValue
        return 'templates/widgets/textInput.html'
   else if angular.isObject propValue
        return 'templates/widgets/formulas.html'
   return

$scope.frequencies = [
    "NONE"
    "DOCUMENT"
    "PERIOD"
    "COLUMN"
  ]

Frequencies.html

这是问题区域。选择显示选项,但单击选项时,模型不会更新。最奇怪的是formula.html 表被更新了。这是因为它们绑定了同一个formObject,但是model没有更新,select被清空了。当我再次单击相同的选项时,select 会正确更新模型。

当您将 select 替换为已注释的 input 时,它可以完美运行。但是用户需要选择频率而不是输入频率。

<div>
    <!--<input ng-model="formObject[item]">-->
    <select data-ng-model="formObject[item]" data-ng-options="frequency for frequency in frequencies"></select>
</div>

公式.html

<div>
    <table class="table table-condensed">
        <thead>
        <tr>
            <th scope="row">&nbsp;</th>
            <th scope="col">title</th>
        </tr>
        </thead>
        <tbody>
            <tr ng-repeat="(key,row) in formObject.formulas">

                <th>{{key}}</th>
                <td ng-repeat="column in row track by $index">
                    <input type="text" ng-model="row[$index]"/>
                </td>
            </tr>
        </tbody>
    </table>
</div>

我希望这足够清楚,所以我希望你能帮助我解决这个问题。

【问题讨论】:

    标签: javascript angularjs coffeescript


    【解决方案1】:

    您需要为 ng-model 使用一个点。 在此处查看我的解释和指向更详细信息的链接: https://stackoverflow.com/a/30850255/3687474

    【讨论】:

    • 当我这样做时,结果是一样的。我用&lt;select data-ng-model="formObject.frequency" data-ng-options="freque....替换了&lt;select data-ng-model="formObject[item]" data-ng-options="freque....
    • 请在 HTML 中添加日志:"FREQUENCY: {{ formObject.frequency }}" 以确保数据设置与否
    • 我这样做了,结果很奇怪。 formulas.html 已更新,但 HTML 中的日志什么也没说...当我第二次单击时,日志也更新为:FREQUENCY: DOCUMENT,例如。 经过更多测试后添加当我使用input type=text 选择频率时,每次击键后都会更新日志
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 2019-01-06
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多