how to url encode expressions of template variable with $interpolate?
Asked Answered
R

1

6

I have a variable

x = "http://example.com?a={{a}}&b={{b}}

This variable is then used in a

ng-src={{x}}

Therefore it is important for me to url encode the variables a and b.

What i do currently is:

var func = $interpolate($scope.x);
            var url = func($scope);
            return  $sce.trustAsResourceUrl(url);

My problem is that when a or b contains spaces they are not url encoded.

How can i tell the $interpolate function to url encode the variables a and b?

Reedbuck answered 2/6, 2015 at 11:29 Comment(0)
B
4

$interpolate service does evaluates the {{}} content and take those value from scope while evaluating scope.

As you want to see the url econded, you are not doing encoding of parameters anywhere. You need to encode your a as well as b in {{}} interpolation using encodeURIComponent of javascript. For that you need to create a wrapper method in scope that will call encodeURIComponent method and return the encode URL, method would be like below.

$scope.encodeContent = function(data){
     return encodeURIComponent(data);
}

Thereafter your URL would look like http://www.example.com/images.jpg?a={{encodeContent(a)}}&b={{encodeContent(b)}}

And while attaching it to src of img tag you need to evaluate interpolation first & then you can make that url as trusted as you are doing now.

Markup

<img src="{{trustedUrl(x)}}" width="50" height="50"/>

Code

$scope.trustedUrl = function(url){
   var interpolatedUrl = $interpolate(url)($scope)
   return $sce.trustAsResourceUrl(interpolatedUrl)
};

Working Plunkr

Bidden answered 9/6, 2015 at 11:54 Comment(2)
@David Michael Gang does you find any issue with this?Bidden
The solution is great and accepted:-) .I found a minor issue with this. This is a template which is filled in by our users in a backoffice, and then instead of a={{a}}&b={{b}} they will have to write a={{encodeContent(a)}}&b={{encodeContent(b)}}. A solution would be that in the backoffice i make a regular expression to transform a={{a}}&b={{b}} to a={{encodeContent(a)}}&b={{encodeContent(b)}}. What do you think ?Reedbuck

© 2022 - 2024 — McMap. All rights reserved.