AngularJS Error: [$interpolate:interr] Can’t interpolate: So I just came across this error when coding some AngularJS. I’ve managed to solve it below.
“Error: [$interpolate:interr] Can’t interpolate:”
“TypeError: Cannot read property ‘toLowerCase’ of undefined”
This is the error, looks like a filter error or something.
As usual the AngularJS docs are super helpful…
Line of code culprit. It’s just calling a filter function which converts the name of a country to lowercase and removes hyphens etc…
tofilename_filter.js
1 2 3 4 5 6 7 8 9 10 11 |
//converts string to hyphenated lowercase angular.module("app").filter('toFilename', function() { return function(str) { return str .toLowerCase() .replace(/ /g,'-') .replace(/[^w-]+/g,''); }; }); |
Did you know about this?
“$sce is a service that provides Strict Contextual Escaping services to AngularJS.”
However: “a[href] and img[src] automatically sanitize their URLs and do not pass them through $sce.getTrusted. SCE doesn’t play a role here.”
“If you are generating your JavaScript from some other templating engine (not recommended, e.g. in issue #4006), remember to escape your regular expression (and be aware that you might need more than one level of escaping depending on your templating engine and the way you interpolated the value.) Do make use of your platform’s escaping mechanism as it might be good enough before coding your own. e.g. Ruby has Regexp.escape(str) and Python has re.escape. Javascript lacks a similar built in function for escaping. Take a look at Google Closure library’s goog.string.regExpEscape(s).”
Yes now we have some idea of what this error is.
Solution.
If we use JavaScripts escape function then the error goes away.
1 2 3 4 5 6 7 8 9 10 11 |
//converts string to hyphenated lowercase angular.module("app").filter('toFilename', function() { return function(str) { return escape(str) .toLowerCase() .replace(/ /g,'-') .replace(/[^w-]+/g,''); }; }); |
I think underscore.string library has a similar function to do this so we could use that instead of our custom filter.
refs: