Created
August 29, 2014 08:51
-
-
Save billyriantono/cd8a47c09b57c4f8e952 to your computer and use it in GitHub Desktop.
angular Factory for String Format , so you can use .Net String Format Mode in your Angular javascript file. based on : https://github.com/ST-Software/Scripts/blob/master/Angular%20Modules/src/stringFormatterModule.js
This file contains 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
angular.module('myApp.stringFormat',[]) | |
.factory('stringFormat', function () { | |
var stringFormat = {}; | |
stringFormat.formatString = function(format,values){ | |
var result = ''; | |
for (var i = 0; ; ) { | |
// Find the next opening or closing brace | |
var open = format.indexOf('{', i); | |
var close = format.indexOf('}', i); | |
if ((open < 0) && (close < 0)) { | |
// Not found: copy the end of the string and break | |
result += format.slice(i); | |
break; | |
} | |
if ((close > 0) && ((close < open) || (open < 0))) { | |
if (format.charAt(close + 1) !== '}') { | |
throw new Error('format stringFormatBraceMismatch'); | |
} | |
result += format.slice(i, close + 1); | |
i = close + 2; | |
continue; | |
} | |
// Copy the string before the brace | |
result += format.slice(i, open); | |
i = open + 1; | |
// Check for double braces (which display as one and are not arguments) | |
if (format.charAt(i) === '{') { | |
result += '{'; | |
i++; | |
continue; | |
} | |
if (close < 0) throw new Error('format stringFormatBraceMismatch'); | |
// Find the closing brace | |
// Get the string between the braces, and split it around the ':' (if any) | |
var brace = format.substring(i, close); | |
var colonIndex = brace.indexOf(':'); | |
var argNumber = parseInt((colonIndex < 0) ? brace : brace.substring(0, colonIndex), 10); | |
if (isNaN(argNumber)) throw new Error('format stringFormatInvalid'); | |
var argFormat = (colonIndex < 0) ? '' : brace.substring(colonIndex + 1); | |
var arg = values[argNumber]; | |
if (typeof (arg) === "undefined" || arg === null) { | |
arg = ''; | |
} | |
// If it has a toFormattedString method, call it. Otherwise, call toString() | |
if (arg.format) { | |
result += arg.format(argFormat); | |
} else | |
result += arg.toString(); | |
i = close + 1; | |
} | |
return result; | |
} | |
return stringFormat; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment