-
-
Save alexandrricov/c0647a6b3d59d64c79d0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * Exemplo: | |
| * var users = [ | |
| * {name: 'Victor Queiroz'}, | |
| * {name: 'João Bosco'}, | |
| * {nickname: {myNickname: 'Ruan Jordão'}} | |
| * ]; | |
| * | |
| * Aplicando o filtro: | |
| * {{ users | pluck:'name | nickname.myNickname' | join:', ' }} | |
| * | |
| * Retorno: | |
| * Victor Queiroz, João Bosco, Ruan Jordão | |
| * | |
| * Dependências: | |
| * - VanillaJS | |
| */ | |
| angular.module('filters', []) | |
| .filter('join', function() { | |
| return function(list, token) { | |
| return (list||[]).join(token); | |
| } | |
| }) | |
| .filter('pluck', function() { | |
| function getProperty(obj, prop) { | |
| return prop.split('.') | |
| .reduce(function (m, i) { | |
| return m && typeof m === 'object' ? m[i] : null; | |
| }, obj); | |
| } | |
| function pluck(objects, propertiesString) { | |
| var results = [], | |
| properties, | |
| propsLn; | |
| if (Array.isArray(objects)) { | |
| properties = propertiesString.split('|'); | |
| propsLn = properties.length; | |
| if (propsLn > 0) { | |
| objects.forEach(function (obj) { | |
| var property, | |
| val, | |
| i; | |
| for (i = 0; i < propsLn; i++) { | |
| property = properties[i].trim(); | |
| val = getProperty(obj, property); | |
| if (val) { | |
| if (Array.isArray(val)) { | |
| results = results.concat(val); | |
| } else { | |
| results.push(val); | |
| } | |
| break; | |
| } | |
| } | |
| }); | |
| } | |
| } | |
| return results; | |
| } | |
| return function(objects, property) { | |
| return pluck(objects, property); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment