From 9c3bff23d4521376016f6b0becdee06804a5168a Mon Sep 17 00:00:00 2001 From: "dkrainas87@gmail.com" Date: Fri, 25 Jul 2014 21:34:03 -0400 Subject: [PATCH] feat($interpolate): use custom toString member if present BREAKING CHANGE: use custom toString implementation when present on object value types. Behavior is consistent with implementations found in other languages such as Ruby, Python, and CoffeeScript. http://rubymonk.com/learning/books/1-ruby-primer/chapters/5-strings/lessons/31-string-basics https://docs.python.org/2/library/stdtypes.html#string-formatting-operations http://coffeescriptcookbook.com/chapters/strings/interpolation Closes #7317 --- src/ng/interpolate.js | 6 +++++- test/ng/interpolateSpec.js | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/ng/interpolate.js b/src/ng/interpolate.js index 016fdfac77e9..31073ef0c911 100644 --- a/src/ng/interpolate.js +++ b/src/ng/interpolate.js @@ -272,7 +272,11 @@ function $InterpolateProvider() { break; } default: { - value = toJson(value); + if(isFunction(value.toString) && value.toString !== Object.prototype.toString && !isArray(value)) { + value = value.toString(); + } else { + value = toJson(value); + } } } diff --git a/test/ng/interpolateSpec.js b/test/ng/interpolateSpec.js index 0bc767339062..17d1d89571b8 100644 --- a/test/ng/interpolateSpec.js +++ b/test/ng/interpolateSpec.js @@ -36,6 +36,21 @@ describe('$interpolate', function() { expect($interpolate('{{ false }}')({})).toEqual('false'); })); + it('should use custom toString when present', inject(function($interpolate, $rootScope) { + var scope = $rootScope.$new(); + scope.a = { + toString: function() { + return 'foo'; + } + }; + + expect($interpolate('{{ a }}')(scope)).toEqual('foo'); + })); + + it('should NOT use toString on array objects', inject(function($interpolate) { + expect($interpolate('{{a}}')({ a: [] })).toEqual('[]'); + })); + it('should return interpolation function', inject(function($interpolate, $rootScope) { var interpolateFn = $interpolate('Hello {{name}}!');