Skip to content

Instantly share code, notes, and snippets.

@asafge
Created November 13, 2013 10:05
Show Gist options
  • Save asafge/7446601 to your computer and use it in GitHub Desktop.
Save asafge/7446601 to your computer and use it in GitHub Desktop.
AngularJS filter that transforms a "foreign key" represented object to a readable string.
angular.module('filters', []).
filter('fromNative', function() {
/**
* Transform any "foreign key" value to its string representation,
* similar to the way ng-options works for a <select> element,
*
* Example:
* Let's say we have an item object with a userID property (item.userID = 5)
* This ID translates to a 'username' from a 'users' object, that looks
* something like this: users = [ {id: 6, name: 'john'}, ... ].
*
* To use in a template, just write out the params
* {[{ item.userID | fromNative:users:'id':'name' }]}
*/
return function(native, options, matchField, valueField) {
if (options) {
for (var i=0; i<options.length; i++) {
if (options[i][matchField] === native) {
return options[i][valueField];
}
}
}
return '';
}
});
@tienbian
Copy link

tienbian commented Oct 6, 2015

how can it work? i tried but it didn't work. just print {[{ item.userID | fromNative:users:'id':'name' }]} in view. Hope you see

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment