【问题标题】:Updating model when selected item is deleted删除选定项目时更新模型
【发布时间】:2014-08-19 17:49:48
【问题描述】:

所以在这个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;
  }
}]);

选择红色并单击“删除红色”时,选择了 -- choose color --选项,但是模型 {{myColor}} is

{"name":"red"}

如果红色被选中并被删除以使其与值一致,我如何将其设置为 null(或空字符串或任何“空”值)?

【问题讨论】:

  • 你需要用同样的方法设置$scope.myColor ="";...?

标签: angularjs


【解决方案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 来解决这个问题。

【讨论】:

  • 我想到了,但这就是 AngularJS 的工作方式吗?如果我需要在修改
  • 这在框架中是reported as a bugexample for select 也显示与您的程序相同的行为。还有一个过时的pull request 来解决这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-18
  • 1970-01-01
  • 2016-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多