UI-Select 删除后未更新模型

UI-Select is not updating the model after a delete

我在 ui-select 中有一个简单的列表,如果我选择删除一个项目,并加载 ui-select 列表中的第一个可用元素,关联的模型不会更新.不知道我错过了什么!

ui-select的定义:

<ui-select on-select="loadSelected($item)" ng-model="selectedDude">
    <ui-select-match placeholder="{{selectedDude.name}}">
      <span> {{selectedDude.name}} </span>
    </ui-select-match>
    <ui-select-choices repeat="d in data | filter: $select.search">
      <span ng-bind-html="d.name  | highlight: $select.search"></span>
    </ui-select-choices>
  </ui-select>

这个函数是我用来删除的函数:

$scope.deleteSelected= function(){
            $scope.data.splice($scope.data.indexOf($scope.selectedDude),1);
            $scope.selectedDude = $scope.data[0];
        };

Check the example in plunker 谢谢你的帮助。

我已经为您修改了 plunkr 以使其正常工作。 https://plnkr.co/edit/rCKCng6ecXiZ8cNGTBlz?p=preview

首先,我在 Array 中添加了一个小的实用方法来从对象列表中删除一个项目:

Array.prototype.remove = function(key, value) {
    var index = -1;
    angular.forEach(this, function(item, i) {
        if (item[key] === value) {
            index = i;
        }
    });

    if (index > -1) {
        this.splice(index, 1);
        return true;
    }
    return false;
};

有两个问题,第一个与您如何从对象数组中删除 selectedDude 有关。

$scope.data.splice($scope.data.indexOf($scope.selectedDude), 1);

因为存储在数组中的 dude 对象引用实例可能与范围变量 selectedDude 所具有的不同。因此,splice 可能无法在您更改其中任何内容时一直正常工作。

所以我们通过索引(使用实用方法)搜索它来精确地删除它。

第二个问题是嵌套的子作用域。阅读 here 了解更多信息。我们通过创建对象 dataStore 并从该对象引用 selectedDude(如 dataStore.selectedDude)来解决此问题,以防止 Javascript.

中的子继承问题