过滤掉选择选项后,角度模型无法更新

Angular model fails to update after select option is filtered out

本文关键字:模型 更新 选择 选项 过滤      更新时间:2023-09-26

试图弄清楚当绑定的选定选项不再存在时,模型为什么不更新。我希望模型的属性更新为undefined/null/empty字符串。

情况:一个select使用筛选器驱动另一个select。选择后,转到原始select并选择另一个选项。Filter将按预期删除第二个select选项,但第二个select上的模型属性将保持不变。

问题:当您传递模型时,它将填充坏的/以前的值。此外,使用Angular验证,需要select。。。该表单在技术上是"有效的",因为模型具有属性的值(以前的值)。

HTML:

<select name="Category" ng-model="selectedCategory" 
       ng-options="item.name as item.name for item in categories">
   <option value="">All Categories</option>
</select>
<select name="SubCategory" ng-model="selectedSubCategory" 
       ng-options="item.name as item.subCategory for item in categories | filter:selectedCategory">
  <option value="">All SubCategories</option>
</select>

型号:

app.controller('MainCtrl', function($scope) {
   $scope.categories = [{
      "id": "1",
      "name": "Truck",
      "subCategory": "Telescope"
   }, {
      "id": "2",
      "name": "Truck",
      "subCategory": "Hazmat"
   }, {
      "id": "3",
      "name": "Van",
      "subCategory": "Mini"
   }];
});

我很确定我可以将ng更改函数与第一个绑定,以强制它更新模型,但有更好的方法吗?

示例Plunker演示问题

试试这个方法:

$scope.$watch('selectedCategory', function(selectedCategory){
    $scope.selectedSubCategory = null;
});