2015年12月17日 星期四

[AngularJS] DropDownList with ng-options

 AngularJS  


Introduction

Refers to

We have several ways to implement the DropDownList with AngularJS.

for array data sources:
label for value in array
select as label for value in array
label group by group for value in array
select as label group by group for value in array track by trackexpr
for object data sources:
label for (key , value) in object
select as label for (key , value) in object
label group by group for (key, value) in object
select as label group by group for (key, value) in object


However, I encountered some problems with it.
Here I will provide a correct way to make a DropDownList (<select> in HTML) with dynamic options and ng-model binding.


Environment

l   AngularJS v1.4.8




▌Samples



Goals

I want to create a DropDownList with dynamic options, which contains a “Please select” as default. When user select a different option excepts “Please select”, the label of the selected value will appear in the webpage.


Failed Attempt

Sounds easy, right? As a starter for AngularJS, I wrote something incorrect like the following codes. (See sample codes HERE)

<div ng-app="app" ng-controller="CustomerCtrl">
  <select ng-model="InChargeId" ng-change="ChangeChargeId()" ng-options="option.CustomerId as option.Title for option in CustomerOptions track by option.CustomerId" />
  <input type="text" ng-show="ShowCustomer" ng-model="InCharge" text="{{InCharge}}" />
</div>

And I try to control the selected value by writing :

$scope.InChargeId = 'Default';


So the result ends in like this …

Default value did not shown when initializing.



Selected value disappeared in the DropDownList



Correct Attempt

The most important thing is that we have to treat the option as an object!
The default value and other options are Objects, so as the ng-model of select.

Furthermore, remove option.CustomerId as …” when using “track by”.

This is the correct codes in HTML:

ng-options="option.Title for option in CustomerOptions track by option.CustomerId"

And use object reference to assign the default value! (JS)

$scope.InChargeId = $scope.CustomerOptions[0];




Reference




沒有留言:

張貼留言