简体   繁体   English

如何使用AngularJS在多选择输入中预选择值

[英]How to pre-select values in multi select input with AngularJS

I have the following HTML: 我有以下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" }). 在CreateSpreadsheetCtrl.init()内部,我们正在加载一个名为“ DepartmentMasters”(csCtrl.DepartmentMasters)的数组,该数组包含对象列表(例如{Id:1,Name:“ Department 1”},{Id:2,Name: “部门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. 同样在init()方法中,我们加载此“ csCtrl.Template”对象,该对象内部有一个名为“ BusinessUnitMappings”(csCtrl.Template.BusinessUnitMappings)的属性,该属性是DepartmentMaster对象的数组。

With the above code, it binds correctly to the model and when you change the selections, csCtrl.Template.BusinessUnitMappings is bound correctly. 使用上面的代码,它可以正确绑定到模型,并且当您更改选择时,csCtrl.Template.BusinessUnitMappings可以正确绑定。

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. 但是,当csCtrl.Template.BusinessUnitMappings预加载有现有对象数组时,当页面最初加载时,它不会在UI中选择它。

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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