Created
March 19, 2014 03:25
-
-
Save litera/9634958 to your computer and use it in GitHub Desktop.
string.Format for AngularJS
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
/* AngularJS string.Format filter | |
* | |
* This filter provides string variable replacement similar to C# string.Format("{0}", "something"); | |
* | |
* Usage: {{ "From model: {0}; and a constant: {1};" | format:model.property:"constant":...:... }} | |
*/ | |
(function (angular) { | |
angular | |
.module("ng") | |
.filter("format", function () { | |
return function (input) { | |
var args = arguments; | |
return input.replace(/\{(\d+)\}/g, function (match, capture) { | |
return args[1*capture + 1]; | |
}); | |
}; | |
}); | |
})(angular); |
@miller45 thanks!
So recant PEMDAS still applies even when the variables aren't numbers
1*"3"+1 = 4
Use args[parseInt(capture, 10) + 1]
which is understood by everyone, not some type conversion magic.
For "typeless" use:
args[Number(capture) + 1]
how to call this filter inside the controller
I guess you probably found a solution for that, however I will answer that for any future questions:
You can use that through $filter. In your controller parameters inject $filter so you can use any filter inside your controller by simply passing its name as a parameter, like this:
var value = $filter('filterName')(input);
Instead of using Number() for the parsing to a number you can add a + in front of it. Like return args[+capture + 1];
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just tried it in the console (enter the funny "typeless" world of javascript)
"1"+1 ="11"
1_"1"+1=2
so the 1_capture forces javascript to evaluate capture as number and then adds 1 resulting in a number.
else "1"+1 means append 1 to the string "1".