2017-08-15 39 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