How can I use angularjs ng-options and ng-model directives to set the select option and detect when the dropdown option is selected or changed? I want to include an extra empty option so that the user can deselect it, and in that case, I want the value in the ng-model expression to be undefined. Is there a way to achieve this without removing the empty option entirely?
In this Plunker example, I intend for the data.model to be undefined when the empty option is selected, but it currently shows as null instead.
https://plnkr.co/edit/d9Jzs4YgqpWHbOxonwa3?p=preview
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-select-ngvalue-production</title>
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="ngvalueSelect">
<div ng-controller="ExampleController">
<form name="myForm">
<label for="ngvalueselect"> ngvalue select: </label>
<select size="6" name="ngvalueselect" ng-model="data.model" multiple>
<option label='' value="{{undefined}}"/>
<option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>
</select>
</form>
<hr>
<pre>model = {{data.model === undefined | json}}</pre><br/>
</div>
</body>
</html>
The corresponding app.js code is as follows:
(function(angular) {
'use strict';
angular.module('ngvalueSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = {
model: null,
availableOptions: [
{value: 'myString', name: 'string'},
{value: 1, name: 'integer'},
{value: true, name: 'boolean'},
{value: null, name: 'null'},
{value: {prop: 'value'}, name: 'object'},
{value: ['a'], name: 'array'}
]
};
}]);
})(window.angular);
Thank you!