I'm facing a problem in upgrading my ng-model in selection.
I have the following HTML:
<div ng-app>
<div ng-controller="Ctrl">
<select ng-model="viewmodel.inputDevice"
ng-options="i.label for i in viewmodel.inputDevices">
</select>
</div>
</div>
And the following code:
function Ctrl($scope) {
// view model
$scope.viewmodel = new function () {
var self = this;
var elem1 = {
value: '1',
label: 'input1'
};
var elem2 = {
value: '2',
label: 'input2'
}
self.inputDevices = [elem1, elem2];
self.inputDevice = {
value: '1',
label: 'input1'
};
};
}
You can use the following JSFiddle
What I want to do is put in inputDevice the same values that the first device has in the collection inputDevices.
I know that I can pass elem1 and it will work however i can't do it since i want to save the selection in Local Storage and than restore it to the ng-model object.
Any suggestion will be grateful
Thanks
You can either store the value instead of the object as Maxim has demonstrated, or you can pull the correct value from the inputDevices
array with something like:
self.inputDevice = self.inputDevices.filter(function(item) {
return item.value == storedValue.value;
})[0];
as per an updated fiddle
The code in the original question works for me:
<div ng-app>
<div ng-controller="Ctrl">
<select ng-model="viewmodel.inputDevice"
ng-options="i.label for i in viewmodel.inputDevices">
</select>
<!-- displays the initial and any further selections
correctly as : {"value":"1","label":"input1"} -->
<span>{{viewmodel.inputDevice}}</span>
</div>
</div>
Your js code code works no doubt, but the viewmodel can be build a little easier:
function Ctrl($scope) {
// view model
$scope.viewmodel = {inputDevices: [
{value: '1', label: 'input1'},
{value: '2', label: 'input2'}
]};
$scope.viewmodel.inputDevice = $scope.viewmodel.inputDevices[0];
}
jsfiddle http://jsfiddle.net/8t2Ln/39/
Instead:
self.inputDevice = {
value: '1',
label: 'input1'
};
I would store index only:
self.inputDevice = 0; // or 1 - second item
and:
<select>
<option ng-repeat="i in viewmodel.inputDevices"
value="{{i.label}}"
ng-selected="viewmodel.inputDevices.indexOf(i) == viewmodel.inputDevice"
>{{i.label}}</option>
</select>
This way will work.
Fixed Demo Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With