0

I am trying to use filter in order to match a newly selected name from a select element using ng-options with the names ID.

The object I'm working with looks like:

 $scope.fish = {1:'Ben', 2: 'Rich', 3:'John'}

Right now the select is set to "John" by default. When the user changes the select option to lets say "Rich", I want the filter function give me back 2 (which is Rich's corresponding ID).

Assume that:

$scope.selectedFish

only stores the name and not the ID for a fish.

JSFiddle

2 Answers 2

1

You can do this,

<div data-ng-app="market">
  <div data-ng-controller="SomeController">
    <select ng-model="selectedFish" ng-options="key as value for (key , value) in fish" ng-change="getIdByName()"></select>
  </div>
</div>

Controller:

app.controller('SomeController', ['$scope', '$filter', function($scope, $filter) {
  $scope.fish = {
    1: 'Ben',
    2: 'Rich',
    3: 'John'
  }
  $scope.getIdByName = function() {
    angular.forEach($scope.fish, function(value, key) {
      if (key == $scope.selectedFish) {
        console.log("selected key is " + $scope.selectedFish + "selected value is " + value);
      }
    });
  }

}]);

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

much appreciated!
1

Try to use following solution

$scope.fish = {1:'Ben', 2: 'Rich', 3:'John'};
$scope.selected = 'Rich';

var getValue = function(){
    var result = "";
    angular.forEach($scope.fish, function(value, key) {
        if (value == $scope.selected) {
           result = key;
        }
    });
    console.log(result);
    return result;
}

Hope this is help.

1 Comment

thanks , you and Sajeetharan basically had the same solutions

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.