angular select 'track by' resets selected - angularjs

I'm struggling getting "selected" to work with 'track by' for Angular select element. I have the following select:
<select id="licenseType" ng-model="selectedLicense"
ng-options="key for (key, value) in licenseMap track by key"
ng-change="doUpdate()">
</select>
with this js:
$scope.selectedLicense = $scope.licenseMap["Please Select"];
The above js works when I get rid of 'track by key' - the initial selection gets preset. With 'track by key' in place the pre-selection is a blank. I need 'track by key' in place to get hold of selected value, it is the only thing that worked so far. I have tried teh following combination so far that did not work:
/*
var license = document.getElementById('licenseType');
license.options.selectedIndex = 1;
license.options[license.options.selectedIndex].selected = true;
$("#licenseType").val("Please Select");
$('#licenseType').children('option[value="1"]').attr('selected', true);
*/
I will most appreciate some help here getting it to work. Thank you.

do something like this: http://codepen.io/alex06/pen/XjarJd
div(data-ng-app="app")
div(ng-controller="appController")
select.form-control(ng-model="selectedItem", ng-options="option.value as option.name for option in typeOptions track by option.value" ng-init="selectedItem=typeOptions[0]")
(function(){
'use strict'
angular
.module('app', [])
.controller('appController', ['$scope', function($scope){
$scope.typeOptions = [
{ name: 'Feature', value: 'feature' },
{ name: 'Bug', value: 'bug' },
{ name: 'Enhancement', value: 'enhancement' }
];
}])
})()
The example is made in jade, but it's almost the same syntax.By the way, if you still want to work with an object instead of array you can also do this:
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"> </script>
<link rel="stylesheet" href="style.css" />
<script type="text/javascript">
angular.module('app', [])
.controller('IndexCtrl', ['$scope', function($scope) {
$scope.types = {
1: "value1",
2: "value2",
5: "value3"
};
}]);
</script>
</head>
<body ng-app="app" ng-controller="IndexCtrl">
<select ng-model="type" ng-options="k as v for (k, v) in types">
<option value="">Please select</option>
</select>
</body>
</html>

Related

Ng-options not displaying anything

I'm using this array on my controller:
var vm = this;
vm.documentGenerationEnum= [
{id:0, name: 'Manual'},
{id:1, name: 'Automatic'}
];
and I'm using this on the html
<select ng-model="vm.editable.DocumentGeneration"
ng-options="option.id as option.name for option in vm.documentGenerationEnum"
class="product-field-input dropdown">
</select>
Though I'm getting an empty dropdown which make no sense to me. I'm pretty sure that the code is well done, because this is not a new topic for me. But I'm not sure what other things could cause this to occur, what other things could I consider?
Works fine in this example:
angular.module("app",[])
.controller("ctrl", function() {
var vm = this;
vm.editable = {};
vm.documentGenerationEnum= [
{id:0, name: 'Manual'},
{id:1, name: 'Automatic'}
];
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl as vm">
<select ng-model="vm.editable.DocumentGeneration"
ng-options="option.id as option.name for option in vm.documentGenerationEnum"
class="product-field-input dropdown">
</select>
<br>Selection={{vm.editable.DocumentGeneration}}
</body>

Show filtered data with angular

I'm a very begginer in AngularJS(1.6) and I need to filter some results from a selected option.
I have to filter cities from states, and until there i'm doing fine. But then I need to filter and show the stores in this city on a list. Does anyone knows how to do It?
My code:
<!DOCTYPE html>
<html data-ng-app="myApp">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
</head>
<body data-ng-controller="testController">
<select id="state" ng-model="stateSrc" ng-options="state for (state, city) in states" ng-change="GetSelectedState()">
<option value=''>State</option>
</select>
<select id="city" ng-model="citySrc" ng-options="city for (city,store) in stateSrc" ng-change="GetSelectedCity()" ng-disabled="!stateSrc">
<option value=''>City</option>
</select>
<select id="city" ng-model="store" ng-options="store for store in citySrc" ng-disabled="!stateSrc || !citySrc">
<option value=''>Store</option>
</select>
<script>
angular
.module('myApp', [])
.run(function($rootScope) {
$rootScope.title = 'myTest Page';
})
.controller('testController', ['$scope', function($scope) {
$scope.states = {
'STATE_1': {
'City_1': ['Store_1', 'Store_2'],
'City_2': ['Store_3', 'Store_4']
},
'STATE-2': {
'City_3': ['Store_1', 'Store_2'],
'City_4': ['Store_3', 'Store_4']
}
};
$scope.GetSelectedState = function() {
$scope.strState = $scope.stateSrc;
};
$scope.GetSelectedCity = function() {
$scope.strCity = $scope.citySrc;
};
}
])
</script>
</body>
</html>
Thank's a lot!
It would be really helpful if you posted what your data source looks like. Assuming citySrc has objects containing arrays of stores, I would set a selectedCity in your controller when you call GetSelectedCity(), and then:
<ul>
<li ng-repeat="store in selectedCity.store">{{store}}</li>
</ul>
This will create list items for each store in your selectedCity object.

how to set a default value in ng-options AngularJS

I would like to set a default value to my select component using angular ng-options
I have seen other topics about this question but i try to use it in my case but not solve..
So i have a select component
<select ng-options="dis.entidade.idEntidade as dis.entidade.nome for dis in distritos" ng-model="distrito.entidade.idEntidade" class="form-control">
<option></option>
</select>
and i would like to set a defaul value.
You can to set at no-model property. Example:
$scope.distrito.entidade.idEntidade = $scope.distritos[0].entidade.idEntidade;
angular.module('app', []).controller('select', function($scope) {
$scope.distrito = {};
$scope.distrito.entidade = {};
$scope.distritos = [{
entidade: {
nome: 'test1',
idEntidade: 1
}
}, {
entidade: {
nome: 'test2',
idEntidade: 2
}
}];
$scope.distrito.entidade.idEntidade = $scope.distritos[0].entidade.idEntidade;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="select">
<select ng-options="dis.entidade.idEntidade as dis.entidade.nome for dis in distritos" ng-model="distrito.entidade.idEntidade" class="form-control">
</select>
</div>
In your controller you can set $scope.distrito.entidade.idEntidade = "defaultValue". Your ng-model is the selected value, so if you don't initialize it in your controller, the value will be undefined. If you set a value to the relevant model during initialization, this will be the default selected value.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.somethingList = [];
$scope.somethingList.push("Something1");
$scope.somethingList.push("Something2");
$scope.somethingList.push("Something3");
$scope.selectedSomething = $scope.somethingList[0];
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-options="something for something in somethingList" ng-model="selectedSomething"></select>
</div>
</body>
</html>
<select ng-options="dis.entidade.idEntidade as dis.entidade.nome for dis in distritos" ng-model="distrito.entidade.idEntidade" class="form-control">
<option>THIS IS YOUR DEFAULT VALUE</option>
If you want to have a default value with some meaning you should do it in your controller, eg:
if (!$scope.distrito.entidade.idEntidade)
$scope.distrito.entidade.idEntidade = 'Some default value';

How to get label=value using ng-options with simple array

I have an array like $scope.years = ['1900', '1901', '1902'];
If I use <select ng-model="chosenYear" ng-options="choice for choice in years"></select>
I get
<option value="0">1900</option>
<option value="1">1901</option>
<option value="2">1902</option>
where index of the array becomes the 'value' of options. How can I have both value and label equal (both being 1900, 1902, 1902, etc) ?
A similar question has an accepted answer, but it doesn't do this thing at all.
Angular version : 1.2.16
What you want is <select ng-model="chosenYear" ng-options="choice as choice for choice in years"></select>
EDIT:
since above does not work in angular 1.2.16 try below
<select ng-model="chosenYear" ng-options="choice for choice in years track by choice"></select>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.years = ['1900', '1901', '1902'];
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="chosenYear" ng-options="choice for choice in years track by choice"></select>
</div>
</body>
</html>
look at this, is similar with your case or you can just use ng-repeat and create value dynamically<option ng-repeat="option in selecteOptions" value="option">{{option}}</option>
Try this
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.years = [{
label: "1900",
value: "1900"
}, {
label: "1901",
value: "1901"
}, {
label: "1902",
value: "1902"
},
];
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Select a year:</p>
<select name="mySelect" id="mySelect" ng-options="option.label for option in years track by option.value" ng-model="selectedCar"></select>
<h1>You selected: {{selectedCar.label}}</h1>
</div>
</body>
</html>
If you don't mind using ng-repeat, use this instead:
<select ng-model="selectedItem">
<option ng-repeat="year in years" value="{{year}}">{{year}}</option>
</select>

angular material md-select using track by but still getting $$hashKey

I'm trying to get rid of the $$hashKey value that angular adds to your model value. According to most sources implementing a track by should solve this issue but I'm doing something wrong.
The vm.productTypes is any array of objects with id properties that are GUIDs.
Resulting model value...
$$hashKey: "object:445"
id: "9e695340-d10a-40ca-9cff-e9a93388912a"
name: "Medical"
type: 1
typeString: "ProductTypes"
HTML Code :
<md-select id="type" ng-model="vm.currentProduct.productType" name="type"
ng-model-options="{trackBy: '$value.id'}"
required>
<md-option ng-repeat="pt in vm.productTypes track by pt.id" ng-value="pt">
{{pt.name}}
</md-option>
</md-select>
Where am I going wrong?
Update:
Seems that the name attribute is causing this strange behavior. Bug?
http://codepen.io/anon/pen/LNpMYJ
Use ng-model-options="{ trackBy: '$value.id' }".
If you are getting list data through $http call, First prepare model object and then load list data.
Or prepare model object and put into an object which is holding hole form data
Link.
<html>
<head>
<title>$$HaskKey Remover</title>
<script src="https://code.angularjs.org/1.3.8/angular.min.js></script>
<script>
var myApp= angular.module('MyApp', []);
myApp.controller('MainCtrl', ['$scope',
function($scope) {
$scope.list = [
{key: "1", name: "Rose"},
{key: {id:2}, name: "Sachin"},
{key: {id:3}, name: "Sandy"}
];
console.log($scope.list);
}
]);
</script>
<head>
<title>Removing $$hashKey when using ng-options</title>
</head>
<body ng-app='MyApp'>
<div ng-controller='MainCtrl'>
<form>
<label for="Select Box">Make a choice of Players:</label>
<select name="selectBx" id="selectBx" ng-model="optionsData"
ng-options="item.name for item in list track by item.key">
</select>
</form>
</div>
</body>
</html>

Resources