Suppose you have a long HTML form and in which you have a select as follow:
<select id="select_id" ng-model="var2model" ng-options="i for i in ['a','b','c','d','e','f','g','h']"></select>
and in the controller you have a variable $scope.res in which store some data to populate the form with. How to set this select default value? I checked the ng-init but couldn't really have it to work. I tried to set ng-init="i === res.my_var"
but no luck. Could someone kindly suggest an approach to solve this?
Here is a snippet from my controller:
var ctrlRes = controllers.controller('ctrlRes', function ($scope, $location, $window, Patient) {
$window.document.title = 'Results';
var path = $location.path().split('/');
var query = path[path.length - 1];
Patient.get({id: query}, function(data){
$scope.res = data;
});
$scope.editMode = false;
$scope.editData = function () {
console.log('editMode on');
$scope.editMode = true;
$scope.my_var = $scope.res.my_var;
};
});
ctrlRes.$inject = ['$scope', 'Patient'];
For select input you are using var2model
as model of the input. So for providing default value you have to assign value to this model object.
For select, in order to assign the default value you have to assign value from array you are using to put values in select options.
So you can do the following:
var ctrlRes = controllers.controller('ctrlRes', function ($scope, $location, $window, Patient) {
$window.document.title = 'Results';
var path = $location.path().split('/');
var query = path[path.length - 1];
Patient.get({id: query}, function(data){
$scope.res = data;
});
$scope.selectArray = ['a','b','c','d','e','f','g','h'];
var index = $scope.selectArray.indexOf($scope.res.my_var);
$scope.var2model = $scope.selectArray[index];
$scope.editMode = false;
$scope.editData = function () {
console.log('editMode on');
$scope.editMode = true;
$scope.my_var = $scope.res.my_var;
};
});
ctrlRes.$inject = ['$scope', 'Patient'];
<select id="select_id" ng-model="var2model" ng-options="i for i in selectArray"></select>