AngularJs Options
select n-options seleccionando un objeto por su id.
by Miguel Roman
HTML
<div ng-app="main">
<div ng-controller="MainController as vm">
<select ng-model="vm.item" ng-options="item as item.name for item in vm.items track by item.id">
<option value="">Seleccione opción</option>
</select>
<p>Item seleccionado: {{ vm.item }}</p>
<div>
<button type="button" ng-click="vm.seleccionar(4)">Seleccionar item 4</button>
</div>
</div>
</div>
JavaScript
function MainController() {
var vm = this;
vm.item = null;
vm.items = [];
vm.seleccionar = seleccionar;
init();
function init() {
vm.items = [
{ id: 1, name: 'Uno' },
{ id: 2, name: 'Dos' },
{ id: 3, name: 'Tres' },
{ id: 4, name: 'Cuatro' }
];
seleccionar(2);
}
// Simula la selección de un valor por defecto
function seleccionar(id) {
// Se puede seleccionar especificando únicamente
// la propiedad indicada como "track by" en el [ng-options]
// el problema puede ser que este método no setea todas
// las propiedades del objeto, en este ejemplo, item
// solo tiene la propiedad "id" pero no la propiedad "name",
// pero cuando la selección es desde el <select /> si settea
// todas las propiedades al item.
vm.item = { id: id };
}
}
angular
.module('main', [])
.controller('MainController', MainController);