【问题标题】:UI-Select is not updating the model after a deleteUI-Select 在删除后不更新模型
【发布时间】:2016-04-08 13:03:01
【问题描述】:

我在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 谢谢你的帮助。

【问题讨论】:

    标签: javascript angularjs angular-ui ui-select


    【解决方案1】:

    我已为您修改了 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 中的子继承问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-15
      • 2019-12-05
      相关资源
      最近更新 更多