0

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];
});
2
  • why dont you simply pass the caption object the user clicked on? Otherwise you would have to search through the array or use the $index property of ng-repeat Commented Jul 19, 2014 at 12:26
  • Unfortunately in my scenario the caption is not useful for what I ultimately need to do. This is a simplification of the problem, but I was just wondering if there was anyway for angular or javascript to get the object number. Commented Jul 19, 2014 at 12:41

2 Answers 2

1

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));
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

Your code was in the body's onload so the module wasn't even properly initialized, that's why your fiddle wasn't working.

$scope.selectedCaption is the select's model and will be automatically updated as the select value changes.

http://jsfiddle.net/LRXkV/2/

1 Comment

oops. Here's the updated fiddle... this still doesn't answer the question I need to find the object # in the array. The reason for this has to do with me needing to reload that array and setting it's initial value to the previous selection. jsfiddle.net/silvajeff/LRXkV/3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.