How can URL encode $ variable interpolation expressions of a template variable?

I have a variable

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

This variable is then used in

ng-src = {{x}}

Therefore, it is important for me that url encodes the variables a and b.

What am I doing now:

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 $ interpolation functions so that url encodes the variables a and b?

+6
source share
1 answer
Service

$interpolate evaluates the contents of {{}} and takes these values ​​from the scope when evaluating the scope.

As you want to see the URL, you are not encoding parameters anywhere. You need to encode a as well as b in {{}} interpolation using encodeURIComponent javascript. To do this, you need to create a shell method in the area that will call the encodeURIComponent method and return the URL code, the method will look below.

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

After that, your URL will look like http://www.example.com/images.jpg?a={{encodeContent(a)}}&b={{encodeContent(b)}}

And by attaching it to the src tag of the img tag, you need to evaluate the interpolation first, and then you can make this URL as reliable as it is 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

+3
source

Source: https://habr.com/ru/post/988384/


All Articles