【问题标题】:ng-options bound variable is not updated after clearing the arrayng-options 绑定变量在清除数组后不更新
【发布时间】:2016-06-08 21:12:11
【问题描述】:

我正在使用一个数组来填充一个带有ng-options 的列表,以及一个绑定到所选项目的属性。清空数组后,绑定变量myObject.selectedItem保持最后选中项的值。

HTML:

<select ng-model="myObject.selectedItem" ng-options="item.Id as item.Name for item in myArrayList | orderBy:'Id'" required>
    <option value="">Select something</option>
</select>

JS:

$scope.myArrayList = [ { Id: 1, Name: "Item 1" }, { Id: 2, Name: "Item 2" } ];
$scope.myObject = { selectedItem: null };

...选择项目2后:

$scope.myArrayList.length = 0;              // Clears the array
console.log($scope.myObject.selectedItem);  // Prints: 2

这是正常行为吗?

【问题讨论】:

    标签: javascript angularjs angularjs-ng-model angularjs-ng-options


    【解决方案1】:

    这是完全正常的行为。

    ng-model 是独立于后备数组呈现的选项的绑定。因此,更改ng-options 的来源对ng-model 绑定属性没有影响。

    如果要清空数组,还需要在设置后备数组长度后将 myObject.selectedItem 设置为 null。

    如果您打算经常执行此类操作并希望它动态更新myObject.selectedItem,您始终可以在myArrayList 上注册一个观察程序,如果长度更新为0,则将selectedItem 设置为null。

    【讨论】:

      【解决方案2】:

      ... .selectedItem 中存储的值被保存,并且与原始值的来源无关。

      所以是的,这是正常和预期的行为。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-16
        • 1970-01-01
        • 1970-01-01
        • 2015-03-02
        • 1970-01-01
        • 1970-01-01
        • 2014-08-13
        • 1970-01-01
        相关资源
        最近更新 更多