Search code examples
javascriptangularjsangularjs-ng-changeangularjs-ng-options

Angular model fails to update after select option is filtered out


Trying to figure out why the model does not update when the bound selected option no longer exists. I would expect the model's property to update to undefined/null/empty string.

Situation: One select drives another select using filter. After selections are made, go to the original select and choose another option. Filter will remove the second select option as expected, but the model property on the second select will be unchanged.

Problem: When you go to pass the model, it will be populated with bad/previous values. In addition, using Angular validation, the select being required...the form is technically "valid" because the model has a value (the previous value) for the property.

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>

Model:

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"
   }];
});

I'm fairly certain I could tie an ng-change function to the first to force it to update the model, but is there a better way?

Example Plunker demonstrating the problem


Solution

  • Try this way:

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