How can I create a directive that automatically preselects an option if only one item is available in the ngOptions scope?
Currently, my code looks like this:
<select id="provider" name="provider" class="form-control"
ng-model="foo.provider"
ng-options="provider.name for provider in providers track by provider.id"
select-first-if-only-one="providers"
required>
<option value="">- Select -</option>
</select>
And here is my directive:
'use strict';
angular.module('app')
.directive('selectFirstIfOnlyOne', function() {
return {
restrict: 'A',
require: 'select',
link: function(scope, elem, attrs, ctrl) {
scope.$watchCollection(attrs.selectFirstIfOnlyOne, function(values) {
if (angular.isDefined(values) && values.length === 1) {
scope.$evalAsync(function() {
ctrl.ngModelCtrl.$setViewValue(values[0]);
});
}
});
}
};
});
The current implementation works, but I'd like to modify it so that array values are not passed directly to the directive, but instead retrieved from ngModel or ngOptions.
I have discovered that SelectController
does not provide methods to access all values from the <select>
, and the same goes for NgModelController
.