I am trying to set the default value in the drop down list of angular JS. Below is my code:
<div >
<select name="actions" id="actions"
ng-options="option.Value for option in Data.Actions"
ng-focus="ActionsLabel = true" ng-blur="ActionsLabel = false;"
ng-model="Data.EmployeeStatusChangeRoutingInput.Action"
/>
<label for="actions"
ng->
Action
</label>
</div>
I want to set the default value to '---' and Id=0. In my controller, I have the following code:
var inputValues = angular.copy($scope.Data.EmployeeStatusChangeRoutingInput);
$scope.Data.EmployeeStatusChangeSaveInSession = {
EffectiveDateString: inputValues.EffectiveDate.toString(),
Action: inputValues.Action.Value,
};
I tried to put this code in my controller in order to make the default value to 0:
$scope.Data.Action = 0;
I wrote the above line right after this line in my controller:
var inputValues = angular.copy($scope.Data.EmployeeStatusChangeRoutingInput);
By putting this line, the selected value of the drop-down list did not change to '---'.
If user does not select any value in the drop down then '---' should be preselected. If user does select some value then that values should pass to the controller.
Any help will be appreciated.
CodePudding user response:
In order to pre-set the value, you have to give the ng-model
an actual value. Here I added
EmployeeStatusChangeRoutingInput: {
Action: 'value3'
}
However, you also need to form your ng-options
so it has name/value pairs, using this syntax:
ng-options="option.Name as option.Value for option in Data.Actions"
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.Data = {
Actions: [{
Value: 'test1',
Name: 'value1'
}, {
Value: 'test2',
Name: 'value2'
}, {
Value: 'test3',
Name: 'value3'
}],
EmployeeStatusChangeRoutingInput: {
Action: 'value3'
}
}
}])
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div >
<select name="actions" id="actions" ng-options="option.Name as option.Value for option in Data.Actions" ng-focus="ActionsLabel = true" ng-blur="ActionsLabel = false;" ng-model="Data.EmployeeStatusChangeRoutingInput.Action"></select>
</div>
</div>