String.format
HTML
<div ng-app="app" ng-controller="ctr">
<div error="'my name is {0} not {1}'" args="[123,234]"></div>
<div error="'my name is {my} not {he}'" args="{my:'me',he:'he'}"></div>
<div error="msg" args="param"></div>
<div error="msg"></div>
</div>
JavaScript
String.format = function () {
var s = arguments[0];
if (arguments.length > 0 && arguments[1] !== undefined) {
var arg = arguments.length == 2 ? arguments[1] : Array.prototype.slice.call(arguments, 1)
for (var key in arg) {
var reg = new RegExp("\\{" + key + "\\}", "gm");
s = s.replace(reg, arg[key]);
}
}
return s;
};
angular.module("app", []).controller("ctr", ["$scope", function ($scope) {
$scope.msg = "my is {0} not {1}";
$scope.param = [123, 567];
}]).directive("error", ["$parse", function ($parse) {
return {
restrict: 'A',
"link": function ($scope, element, iAttrs) {
var fun = function () {
var msg = $parse(iAttrs.error)($scope);
var args = $parse(iAttrs.args)($scope);
var text = String.format(msg, args);
element.text(text);
};
iAttrs.$observe("error", fun);
iAttrs.$observe("args", fun);
}
};
}]);
var a = String.format("{0} {1}", "me", "you");
console.log(a);
var b = String.format("I am {me}, your name is {you}?", {
me: "me",
you: "you"
});
console.log(b);
var c = String.format("I am {0}, your name is {1},not {2}?", "me", "you", "she");
console.log(c);