I load an array of objects into a select box. The user makes a selection... how can identify which array object they chose so I can use it in downstream work?
For example if user chooses the 2nd object in the array... how can identify the selection was the second item in the array?
http://jsfiddle.net/silvajeff/LRXkV/3/
angular.module('demoApp', []).controller('DemoController', function ($scope) {
$scope.captions = [{
name: 'A',
value: 'a'
}, {
name: 'B',
value: 'b'
}, {
name: 'C',
value: 'c'
}, {
name: 'D',
value: 'd'
}, {
name: 'E',
value: 'e'
}];
//how could I determine that 3 should be the number used in the expression below
$scope.selectedCaption = $scope.captions[3];
});
You can wotch for index of selected item in array:
$scope.$watch(function() {
return $scope.captions.indexOf($scope.selectedCaption);
},
function(newVal, oldVal) {
if (newVal != oldVal) {
alert('New index of selected caption :' + newVal);
}
});
Or just watch for selectedCaption
anf get index in listener function:
$scope.$watch('selectedCaption',
function (newVal, oldVal) {
if (newVal != oldVal) {
alert('New index of selected caption :' + $scope.captions.indexOf(newVal));
}
});