使用默认选定的其他数据源时,从 ui-select 选项中删除重复项



好的,我知道这之前已经涵盖过,我已经尝试了所有这些结果,但无法让它们在我的情况下工作:

我正在尝试对多个数据源使用角度 ui-select - 一个用于默认选项,另一个用于可选选项,但不应发生重复

例如:

对于 ng-model 绑定,我在$scope上使用了一个空数组,该数组填充了与来自名为"类别"的 API 端点的帖子关联的类别。

对于默认选择的选项,我正在获取已经与 post 对象关联的类别 - 这来自另一个 api 端点。

我的控制器

app.controller('MainCtrl', function($scope, $http) {
    $scope.selectedTerms = [];
$http.get('currentTerms.json').then(function(currentTermsObj){
    var currentTerms = currentTermsObj.data;
        currentTerms.map(function(currentTerm){
        var currentPostTerm = currentTerm;
        $scope.selectedTerms.push(currentPostTerm); 
        });
  });

$http.get('possibleTerms.json').then(function(possibleTermsObj){
  $scope.possibleTerms = possibleTermsObj.data;
  });

我的网页:

    <ui-select
        multiple
        ng-model="selectedTerms">
        <ui-select-match placeholder="Select Category...">{{$item.name}}</ui-select-match>
        <ui-select-choices
            repeat="term in possibleTerms">
        {{term.name}}
        </ui-select-choices>
    </ui-select>

问题是,无论我做什么,总会有重复和角度怪胎,并出现以下错误:

"错误:[ngRepeat:dupes] 不允许在中继器中重复。用 '跟踪依据'表达式以指定唯一键。

哦,我试过使用"按$index跟踪",但没有运气。

如何使用两个不同的数据源并让 ui-select 从选项下拉列表中删除重复项(当它们已存在于另一个数据源中时?

Plnkr演示我的问题:http://plnkr.co/edit/WDthr7?p=preview

"<ui-select-choices/>"中添加过滤器

<ui-select-choices repeat="color in availableColors | filter:$select.search">

演示UISELECT - 普伦克

(或)在您的 <ui-select-choices/> 标签中使用按 ID 或名称跟踪(这个对我有用)

<ui-select multiple ng-model="selectedTerms">
        <ui-select-match placeholder="Select Category...">{{$item.name}}</ui-select-match>
 <ui-select-choices repeat="term in possibleTerms track by term.name">  
 {{term.name}}
        </ui-select-choices>
    </ui-select>

另一种方法是自己合并它们。 请参阅 http://plnkr.co/edit/NPdxYK8fqCPMhsKXRSGH?p=preview

在控制器中:-

$http.get('currentTerms.json').then(function(currentTermsObj){
    var currentTerms = currentTermsObj.data;
        currentTerms.map(function(currentTerm){
        var currentPostTerm = currentTerm;
        $scope.selectedTerms.push(currentPostTerm); 
        });
        $http.get('possibleTerms.json').then(function(possibleTermsObj){
            $scope.possibleTerms = possibleTermsObj.data;
            for(var i = 0; i < $scope.possibleTerms.length; i++){
              if(i < $scope.selectedTerms.length){
              $scope.possibleTerms[i] = $scope.selectedTerms[i];
            }
         }   
      });
  });

请注意,为了节省时间,上述合并逻辑仅适用于此示例。

最新更新