删除所选项目时更新模型

时间:2014-08-18 15:41:02

标签: angularjs

所以在这个example中我有一个简单的选择

<select ng-model="myColor" ng-options="color.name for color in colors">
    <option value="">-- choose color --</option>
</select>

使用三种颜色和一个按钮删除最后一个

<button ng-click="delRed()">Delete red</button><br/>

JS代码看起来像那样

angular.module('selectExample', [])
.controller('ExampleController', ['$scope', function($scope) {
  $scope.colors = [
    {name:'black'},
    {name:'white'},
    {name:'red'},
  ];
  $scope.myColor = $scope.colors[2]; // red
  $scope.delRed = function(){        
    $scope.colors.length = 2;
  }
}]);

选择红色并单击&#34;删除红色&#34;已选择-- choose color --选项,但模型{{myColor}}

{"name":"red"}

如果选择红色并将其删除以使其与值保持一致,如何将其设置为null(或空字符串或任何&#34;空&#34;值)?

1 个答案:

答案 0 :(得分:1)

如果它等于您要删除的元素,为什么不覆盖myColor

  $scope.delRed = function(){
    if ($scope.myColor === $scope.colors[$scope.colors.length - 1]) {
      $scope.myColor = undefined;
    }
    // IMO Overriding .length of an array to delete an element is a bit of a hack
    $scope.colors = $scope.colors.slice(0, $scope.colors.length - 1);
  }

http://plnkr.co/edit/YEOwFcrV9OoV4jI8Zlmn?p=preview


更新:框架中已reported as a bugexample for select on Angular docs也显示与上述程序相同的行为。还有一个过时的pull request来解决这个问题。