Reputation: 3994
I have a select with a filter to format the display text and I need to pass the selected value to the controller, but I want to pass the "id" of selected item:
<select
ng-model="my_field"
ng-options="q.name as (q.name | filter1 | filter2) for q in my_fields track by q.id"
ng-change="controllerMethod(my_field)"
required>
</select>
// Controller
function controllerMethod(selected_field){
console.log(selected_field);
}
$scope.controllerMethod = controllerMethod;
// Filters
angular.module('app')
.filter('filter1', function(){
return function(str_value) {
return str_value ? str_value.split('_').join(' ') : "";
}
})
.filter('filter2', function(){
return function(str_value) {
return (!!str_value) ? str_value.charAt(0).toUpperCase() + str_value.substr(1).toLowerCase() : '';
}
})
Before I add this filter it was passing all object to the controller. Now, it's passing the "q.name" (the label). How can I pass the id of selected object?
Thanks!
Upvotes: 1
Views: 400
Reputation: 81
I believe you need you change your ng-options
to the following:
ng-options="q as (q.name | filter1 | filter2) for q in my_fields track by q.id"
With the way you have yours set up, the track by
expression evaluates to q.name.id
which will be undefined. The code I've added above should evaluate to q.id
which I believe is what you're after. Check this jsfiddle to see if that's what you're wanting.
Upvotes: 2