Skip to content

Instantly share code, notes, and snippets.

@marchrius

marchrius/app.js

Forked from imjoshholloway/app.js
Created Jul 8, 2016
Embed
What would you like to do?
ngPluralize but with support for HTML
angular.module('myApp', ['ngPluralizeHtml'])
function AppController() {
var vm = this;
vm.count = 10;
}
.controller('AppController', AppController);
(function (angular, undefined) {
function PluralizeDirective($locale, $interpolate, $log) {
var BRACE = /{}/g,
IS_WHEN = /^when(Minus)?(.+)$/;
return {
restrict: 'EA',
link: function (scope, element, attr) {
var numberExp = attr.count,
whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
offset = attr.offset || 0,
whens = scope.$eval(whenExp) || {},
whensExpFns = {},
startSymbol = $interpolate.startSymbol(),
endSymbol = $interpolate.endSymbol(),
braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
watchRemover = angular.noop,
lastCount;
angular.forEach(attr, function (expression, attributeName) {
var tmpMatch = IS_WHEN.exec(attributeName);
if (tmpMatch) {
var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
whens[whenKey] = element.attr(attr.$attr[attributeName]);
}
});
angular.forEach(whens, function (expression, key) {
whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
});
scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
var count = parseFloat(newVal);
var countIsNaN = isNaN(count);
if (!countIsNaN && !(count in whens)) {
// If an explicit number rule such as 1, 2, 3... is defined, just use it.
// Otherwise, check it against pluralization rules in $locale service.
count = $locale.pluralCat(count - offset);
}
// If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
// In JS `NaN !== NaN`, so we have to exlicitly check.
if ((count !== lastCount) && !(countIsNaN && isNaN(lastCount))) {
watchRemover();
var whenExpFn = whensExpFns[count];
if (whenExpFn === undefined) {
$log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
watchRemover = angular.noop;
updateElementText();
} else {
watchRemover = scope.$watch(whenExpFn, updateElementText);
}
lastCount = count;
}
});
function updateElementText(newText) {
element.html(newText || '');
}
}
};
}
angular.module('ngPluralizeHtml', []).directive('ngPluralizeHtml', PluralizeDirective);
})(angular);
<div ng-controller="AppController as ctrl">
<ng-pluralize-html count="ctrl.count"
when="{'0': 'No items were found','one': '<strong>One</strong> item was found', 'other': '<strong>{}</strong> items were found'}">
</ng-pluralize-html>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment