Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate url encoded anchor links with AngularJS?

<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.

like image 271
randomguy Avatar asked Jan 24 '13 23:01

randomguy


People also ask

What is %20 URL encode?

URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.

Should I use encodeURI or encodeURIComponent?

If you have a complete URL, use encodeURI . But if you have a part of a URL, use encodeURIComponent .

What is URL encoded in node JS?

urlencoded() function is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on body-parser. Parameter: The options parameter contains various property like extended, inflate, limit, verify etc.

What is decoder in angular?

Decode URL: URL Decoding refers to the process of replacing the “%-based escape sequence” characters with their normal representation in the encoded URLs. URL can easily be encoded or decoded with the help of AngularJS. Given an encoded URL and the task is to decode the encoded URL using AngularJS.


2 Answers

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)

like image 139
Tosh Avatar answered Oct 19 '22 14:10

Tosh


@Tosh's solution will return #/search?query=undefined if address is undefined in

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

If you prefer to get an empty string instead for your query you have to extend the solution to

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

This will return #/search?query= if address is undefined.

like image 23
asmaier Avatar answered Oct 19 '22 13:10

asmaier