angular filter
by Akram kamal
HTML
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://www.ascotproject.com/vendor/javascripts/jquery.hammer.js"></script>
<link rel="stylesheet" href="http://www.eyecon.ro/bootstrap-slider/css/bootstrap.css">
<link rel="stylesheet" href="http://www.eyecon.ro/bootstrap-slider/css/slider.css">
<script src="http://www.eyecon.ro/bootstrap-slider/js/bootstrap-slider.js"></script>
<div ng-app="myApp">
All Nas needs is {{1 | pluralize:'Mic'}}
<br>
In the last week I have eaten {{0 | pluralize:'sandwich'}}
<br>
At most I can carry {{2 | pluralize:'box'}}
<br>
I've been to {{1 | pluralize:'city'}} in the last month
<br>
I still have {{4 | pluralize:'syllabus'}} from college
<br>
I know the lyrics to the {{12 | pluralize:'Day'}} of Christmas - there are {{2 | pluralize:'turtle dove'}}
</div>
JavaScript
angular.
module('myApp', []).
filter('pluralize', function() {
return function(ordinal, noun) {
if (ordinal == 1) {
return ordinal + ' ' + noun;
} else {
var plural = noun;
if (noun.substr(noun.length - 2) == 'us') {
plural = plural.substr(0, plural.length - 2) + 'i';
} else if (noun.substr(noun.length - 2) == 'ch' || noun.charAt(noun.length - 1) == 'x' || noun.charAt(noun.length - 1) == 's') {
plural += 'es';
} else if (noun.charAt(noun.length - 1) == 'y' && ['a','e','i','o','u'].indexOf(noun.charAt(noun.length - 2)) == -1) {
plural = plural.substr(0, plural.length - 1) + 'ies';
} else if (noun.substr(noun.length - 2) == 'is') {
plural = plural.substr(0, plural.length - 2) + 'es';
} else {
plural += 's';
}
return ordinal + ' ' + plural;
}
};
});