|
173 | 173 | </example>
|
174 | 174 | */
|
175 | 175 | var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
|
176 |
| - var BRACE = /{}/g; |
| 176 | + var BRACE = /{}/g, |
| 177 | + IS_WHEN = /^when(Minus)?(.+)$/; |
| 178 | + |
177 | 179 | return {
|
178 | 180 | restrict: 'EA',
|
179 | 181 | link: function(scope, element, attr) {
|
180 | 182 | var numberExp = attr.count,
|
181 | 183 | whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
|
182 | 184 | offset = attr.offset || 0,
|
183 |
| - whens = scope.$eval(whenExp) || {}, |
184 |
| - whensExpFns = {}, |
| 185 | + whens = scope.$eval(whenExp) || createMap(), |
| 186 | + whensExpFns = createMap(), |
185 | 187 | startSymbol = $interpolate.startSymbol(),
|
186 | 188 | endSymbol = $interpolate.endSymbol(),
|
187 |
| - isWhen = /^when(Minus)?(.+)$/; |
| 189 | + tmpMatch; |
188 | 190 |
|
189 | 191 | forEach(attr, function(expression, attributeName) {
|
190 |
| - if (isWhen.test(attributeName)) { |
191 |
| - whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] = |
192 |
| - element.attr(attr.$attr[attributeName]); |
| 192 | + tmpMatch = IS_WHEN.exec(attributeName); |
| 193 | + if (tmpMatch) { |
| 194 | + var whenKey = lowercase((tmpMatch[1] ? '-' : '') + tmpMatch[2]); |
| 195 | + whens[whenKey] = element.attr(attr.$attr[attributeName]); |
193 | 196 | }
|
194 | 197 | });
|
195 |
| - forEach(whens, function(expression, key) { |
196 |
| - whensExpFns[key] = |
197 |
| - $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' + |
198 |
| - offset + endSymbol)); |
199 |
| - }); |
| 198 | + for (var key in whens) { |
| 199 | + var expr = startSymbol + numberExp + '-' + offset + endSymbol; |
| 200 | + whensExpFns[key] = $interpolate(whens[key].replace(BRACE, expr)); |
| 201 | + } |
200 | 202 |
|
201 |
| - scope.$watch(function ngPluralizeWatch() { |
202 |
| - var value = parseFloat(scope.$eval(numberExp)); |
| 203 | + scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) { |
| 204 | + var value = parseFloat(newVal); |
| 205 | + var text = ''; |
203 | 206 |
|
204 | 207 | if (!isNaN(value)) {
|
205 | 208 | //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
|
206 | 209 | //check it against pluralization rules in $locale service
|
207 | 210 | if (!(value in whens)) value = $locale.pluralCat(value - offset);
|
208 |
| - return whensExpFns[value](scope); |
209 |
| - } else { |
210 |
| - return ''; |
| 211 | + text = whensExpFns[value](scope); |
211 | 212 | }
|
212 |
| - }, function ngPluralizeWatchAction(newVal) { |
213 |
| - element.text(newVal); |
| 213 | + |
| 214 | + element.text(text); |
214 | 215 | });
|
215 | 216 | }
|
216 | 217 | };
|
|
0 commit comments