当过滤条件改变时,AngularJS选择模型不更新

时间:2016-08-30 10:43:03

标签: angularjs angularjs-scope

我花了好几个小时试图找到以下问题的答案。

JSFiddle here

截图:

enter image description here

我有两个选择:

<label>Animal</label>
<select ng-model='myAnimal' ng-options="animal for animal in animals">
  <option value="">-- Please Select --</option>
</select>

<label>Action</label>
<select ng-model="myAction" ng-options="action as action.name for action in actions | filter: { usedBy: myAnimal } track by action.id">
  <option value="">-- Please Select --</option>
</select>

使用此javascript:

angular.module('CMS', [])
.controller('CMSCtrl', function ($scope) {

    $scope.animals = ["cat", "dog"];
    $scope.actions = [
       {id: 1, name: "walk", usedBy: 'cat,dog'},
       {id: 2, name: "meow", usedBy: 'cat'},
       {id: 3, name: "bark", usedBy: 'dog'}
    ];

  $scope.myAnimal = null;
  $scope.myAction = null;
});

根据用户在第一个选择中选择的内容,过滤第二个选择中显示的值。

问题:选择动物“狗”和动作“树皮”。然后选择动物“猫”。 AngularJS将动作设置为“ - 请选择 - ”这是正确的(因为猫不能吠叫),但模型$ scope.action没有更新。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

这是解决方案

以下是更新的 Demo

TableView
angular.module('CMS', [])
  .controller('CMSCtrl', function ($scope) {

  $scope.animals = ["cat", "dog"];
  $scope.actions = [
    {id: 1, name: "walk", usedBy: 'cat,dog'},
    {id: 2, name: "meow", usedBy: 'cat'},
    {id: 3, name: "bark", usedBy: 'dog'}
  ];

  $scope.myAnimal = null;
  $scope.myAction = null;
  $scope.callChange = function(){
  	if($scope.myAction && $scope.myAction.id != 1){
      	$scope.myAction = null;
    }
  }
});