2017-08-15 137 views
-1

我有一个多选。我有两个不同的数组。我想要多选与来自选定的值。AngularJS ng-selected问题

我想从数组中搜索ng-repeat id如果找到,则它变为true,并且值将与选定的一起出现。

我AngularJS代码

<script> 
     var app = angular.module('myApp', []); 
    app.controller('MainCtrl', function($scope, $http) { 

     $scope.name = "John Brad"; 

     $scope.important_selection = { 
        "error": false, 
        "client_data": { 
        "important": [ 
         { 
          "id": 10, 
          "name": "Socially Responsible" 
         }, 
         { 
          "id": 8, 
          "name": "LBGT" 
         }, 
         { 
          "id": 4, 
          "name": "Education" 
         }, 
         { 
          "id": 2, 
          "name": "Retirement" 
         } 
        ] 
       }, 
       "status_code": 200 
       }; 

    $scope.importants_series = { 
       "error": false, 
       "important": [ 
        { 
         "id": 1, 
         "name": "Investment" 
        }, 
        { 
         "id": 2, 
         "name": "Retirement" 
        }, 
        { 
         "id": 3, 
         "name": "Insurance" 
        }, 
        { 
         "id": 4, 
         "name": "Education" 
        }, 
        { 
         "id": 5, 
         "name": "Tax" 
        }, 
        { 
         "id": 6, 
         "name": "Estate" 
        }, 
        { 
         "id": 7, 
         "name": "Business" 
        }, 
        { 
         "id": 8, 
         "name": "LBGT" 
        }, 
        { 
         "id": 9, 
         "name": "Offshore" 
        }, 
        { 
         "id": 10, 
         "name": "Socially Responsible" 
        }, 
        { 
         "id": 11, 
         "name": "Divorce" 
        } 
       ], 
       "status_code": 200 
      };   
    }); 
    </script> 

我的HTML代码

<select name="important[]" class="form-control" multiple="" required> 
     <option ng-selected="important_selection.important.find(item => item.id === important.id)" ng-repeat="important in importants_series.important" value="{{important.id}}">{{important.name}}</option> 
    </select> 

现在我想搜索ID阵列,如果真,那么它会被选中。 我有问题ng-selected

Plunker Link for more detailshttps://plnkr.co/edit/BUnUNqr0IevJ5BkslZNM?p=preview

任何帮助将升值感谢。

回答

1

为便于数据绑定,您应该使用ng-optionsng-model中的select

<select name="important[]" class="form-control" multiple="" required 
    ng-options="important.name for important in importants_series.important" 
    ng-model="important_selection.client_data.important"></select> 

不幸的是ng-model仅供对象引用相等检查,所以我们需要额外的步骤,以从选择阵列本身

var oldArray = $scope.important_selection.client_data.important; 

    $scope.important_selection.client_data.important = []; 

    oldArray.forEach(function(item) { 
    var refItem = $scope.importants_series.important.find(function(i) { 
     return i.id == item.id; 
    }); 

    $scope.important_selection.client_data.important.push(refItem); 
    }); 

重新分配数据,也可以将其分配到一个新的数组来代替。

Working plunker