简体   繁体   中英

How to pre-select values in multi select input with AngularJS

I have the following HTML:

<div ng-controller="CreateSpreadsheetCtrl as csCtrl" ng-init="csCtrl.init()">
    <select multiple="multiple" style="height:100px;" class="form-control" 
            ng-model="csCtrl.Template.BusinessUnitMappings"
            ng-options="department as department.LocalizedName for department in csCtrl.DepartmentMasters">
    </select>
</div>

Inside the CreateSpreadsheetCtrl.init(), we are loading an array called "DepartmentMasters" (csCtrl.DepartmentMasters) which contains a list of objects (eg {Id:1, Name: "Department 1" }, {Id:2, Name: "Department 2" }).

Also in the init() method, we load this "csCtrl.Template" object, which has a property inside it called "BusinessUnitMappings" (csCtrl.Template.BusinessUnitMappings), which is an array of DepartmentMaster objects.

With the above code, it binds correctly to the model and when you change the selections, csCtrl.Template.BusinessUnitMappings is bound correctly.

However, when csCtrl.Template.BusinessUnitMappings is pre-loaded with an existing array of objects, it doesn't select it in the UI when the page initially loads.

Change the expression to :

ng-options="department as department.Name for department in csCtrl.DepartmentMasters track by department.Id"

Working Demo :

 var myApp = angular.module('myApp', []); myApp.controller('MyCtrl',function($scope) { var ctrl = this; ctrl.DepartmentMasters = [ {Id:1, Name: "Department 1" }, {Id:2, Name: "Department 2" }, {Id:3, Name: "Department 3" }, {Id:4, Name: "Department 4" }, {Id:5, Name: "Department 5" } ]; ctrl.Template = { "BusinessUnitMappings" : [ {Id:2, Name: "Department 2" }, {Id:3, Name: "Department 3" } ] } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="MyCtrl as csCtrl"> <select multiple="true" style="height:100px;" class="form-control" ng-model="csCtrl.Template.BusinessUnitMappings" ng-options="department as department.Name for department in csCtrl.DepartmentMasters track by department.Id"></select> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM