如何将整个选择选项对象设置为模型?

时间:2017-07-07 19:58:16

标签: angularjs multi-select

我发现所选模型只包含选项对象属性的id属性。所选模型是否可以包含整个对象?

HTML

<div ng-dropdown-multiselect="" options="exampleData" selected-model="exampleModel"></div>

JavaScript

$scope.exampleModel = []; 
$scope.exampleData = [ 
   {id: 1, code: 'CA': label: "California"}, 
   {id: 2, code: 'MN' label: "Minnesota"}, 
   {id: 3, code: 'NY', label: "New York"} ];

因此,在这种情况下,如果我选择第一个选项,模型将变为以下内容:

$scope.exampleModel = [{"id":"CA"}]

我需要模型包含整个选项对象,如下所示:

$scope.exampleModel = [{id: 1, code: 'CA': label: "California"}]

2 个答案:

答案 0 :(得分:2)

您可以在onSelectionChanged回拨事件中更新它。

var app = angular.module('app', ['angularjs-dropdown-multiselect']);

app.controller('MainCtrl', function($scope) {
  $scope.exampleModel = [];
  $scope.exampleData = [{
    id: 1,
    code: 'CA',
    label: "California"
  }, {
    id: 2,
    code: 'MN',
    label: "Minnesota"
  }, {
    id: 3,
    code: 'NY',
    label: "New York"
  }];
  $scope.exampleEvents = {
    onSelectionChanged: function() {

      $scope.exampleModel.forEach(function(selectedData) {
        var data = $scope.exampleData.find(function(item) {
          return item.id == selectedData.id;
        });
        if (data != null) {
          angular.copy(data, selectedData);
        }
      });
      console.log("Change:", $scope.exampleModel);
    }
  }
});
<!DOCTYPE html>
<html ng-app="app">

<head>
  <link data-require="bootstrap@*" data-semver="3.3.2" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
  <script data-require="jquery@2.1.3" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
  <script data-require="bootstrap@*" data-semver="3.3.2" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
  <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angularjs-dropdown-multiselect/1.11.8/angularjs-dropdown-multiselect.min.js"></script>
</head>

<body ng-controller="MainCtrl">
  <div ng-dropdown-multiselect="" options="exampleData" selected-model="exampleModel" events="exampleEvents"></div>
</body>

</html>

答案 1 :(得分:1)

将externalIdProp:''添加到如下所示的其他设置中: {enableSearch:true,scrollableHeight:“ 400px”,scrollable:true,externalIdProp:“}}

这是链接https://github.com/dotansimha/angularjs-dropdown-multiselect/issues/396