How to generate url encoded anchor links with AngularJS?

randomguy picture randomguy · Jan 25, 2013 · Viewed 92.1k times · Source
<a href="#/search?query={{address}}" ng-repeat="address in addresses">
  {{address}}
</a>

generates links that are not url encoded if I understand correctly. What is the proper way to encode #/search?query={{address}}?

Example address is 1260 6th Ave, New York, NY.

Answer

Tosh picture Tosh · Jan 25, 2013

You can use the native encodeURIComponent in javascript. Also, you can make it into a string filter to utilize it.

Here is the example of making escape filter.

js:

var app = angular.module('app', []);
app.filter('escape', function() {
  return window.encodeURIComponent;
});

html:

<a ng-href="#/search?query={{address | escape}}">

(updated: adapting to Karlies' answer which uses ng-href instead of plain href)