Skip to content

Instantly share code, notes, and snippets.

@litera
Created March 19, 2014 03:25
Show Gist options
  • Save litera/9634958 to your computer and use it in GitHub Desktop.
Save litera/9634958 to your computer and use it in GitHub Desktop.
string.Format for AngularJS
/* 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);
@bdairy
Copy link

bdairy commented Feb 9, 2016

how to call this filter inside the controller

@alisonjonck
Copy link

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);

@sorskoot
Copy link

sorskoot commented Aug 2, 2016

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