How can I invoke encodeURIComponent from AngularJS template in HTML?

The encodeURIComponent() function is a JavaScript method that encodes special characters in URI components by replacing them with UTF-8 escape sequences. In AngularJS templates, you can invoke this function through controller methods, filters, or direct expressions to safely encode URLs, query parameters, and other URI components.

Each time a special character appears in a URI component, the encodeURIComponent() function replaces it with one, two, three, or four escape sequences representing the character's UTF-8 encoding (four escape sequences are used for characters composed of two "surrogate" characters).

Syntax

Following is the syntax for encodeURIComponent()

encodeURIComponent(uriComponent)

Parameters

uriComponent − Any value including a string, number, boolean, null, or undefined. The uriComponent is converted to a string before encoding.

Return Value

Returns a new string representing the provided string encoded as a URI component.

Method 1: Using Controller Function

The most common approach is to create a function in your AngularJS controller that calls encodeURIComponent() and binds the result to the scope.

Example

Following example demonstrates encoding a URL using a controller function −

<!DOCTYPE html>
<html>
<head>
   <title>AngularJS encodeURIComponent - Controller Method</title>
   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <div ng-app="encodeApp" ng-controller="EncodeController">
      <h2>URL Encoding with AngularJS</h2>
      <p><strong>Original URL:</strong> {{originalUrl}}</p>
      <p><strong>Encoded URL:</strong> {{encodedUrl}}</p>
      <button ng-click="encodeUrl()" style="padding: 8px 16px; margin-top: 10px;">Encode URL</button>
   </div>

   <script>
      var app = angular.module('encodeApp', []);
      app.controller('EncodeController', function($scope) {
         $scope.originalUrl = 'https://www.tutorialspoint.com/search?q=angular js&type=tutorial';
         $scope.encodedUrl = '';
         
         $scope.encodeUrl = function() {
            $scope.encodedUrl = encodeURIComponent($scope.originalUrl);
         };
      });
   </script>
</body>
</html>

When you click the "Encode URL" button, the original URL gets encoded and displayed −

Original URL: https://www.tutorialspoint.com/search?q=angular js&type=tutorial
Encoded URL: https%3A%2F%2Fwww.tutorialspoint.com%2Fsearch%3Fq%3Dangular%20js%26type%3Dtutorial

Method 2: Using Custom Filter

You can create a custom AngularJS filter to use encodeURIComponent() directly in templates without controller functions.

Example

Following example shows how to create and use a custom encoding filter −

<!DOCTYPE html>
<html>
<head>
   <title>AngularJS encodeURIComponent - Custom Filter</title>
   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <div ng-app="filterApp" ng-controller="FilterController">
      <h2>URL Encoding with Custom Filter</h2>
      <div style="background: #f5f5f5; padding: 15px; border-radius: 5px; margin: 10px 0;">
         <p><strong>Search Query:</strong> {{searchQuery}}</p>
         <p><strong>Encoded Query:</strong> {{searchQuery | encodeUri}}</p>
         <p><strong>Full Search URL:</strong> 
            https://example.com/search?q={{searchQuery | encodeUri}}
         </p>
      </div>
      <input ng-model="searchQuery" placeholder="Enter search terms" style="padding: 8px; width: 300px;">
   </div>

   <script>
      var app = angular.module('filterApp', []);
      
      app.filter('encodeUri', function() {
         return function(input) {
            return input ? encodeURIComponent(input) : '';
         };
      });
      
      app.controller('FilterController', function($scope) {
         $scope.searchQuery = 'javascript & angular tutorials';
      });
   </script>
</body>
</html>

The custom filter automatically encodes the input as you type, showing real-time URL encoding −

Search Query: javascript & angular tutorials
Encoded Query: javascript%20%26%20angular%20tutorials
Full Search URL: https://example.com/search?q=javascript%20%26%20angular%20tutorials

Method 3: Direct Template Expression

For simple cases, you can create a scope function and call it directly in template expressions, though this is less efficient for repeated use.

Example

Following example demonstrates direct function calls in template expressions −

<!DOCTYPE html>
<html>
<head>
   <title>AngularJS encodeURIComponent - Direct Expression</title>
   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <div ng-app="directApp" ng-controller="DirectController">
      <h2>Dynamic URL Generation</h2>
      <div style="margin: 15px 0;">
         <label>Page Name: </label>
         <input ng-model="pageName" style="padding: 5px; margin-left: 10px;">
      </div>
      <div style="margin: 15px 0;">
         <label>Category: </label>
         <input ng-model="category" style="padding: 5px; margin-left: 10px;">
      </div>
      <div style="background: #e8f4f8; padding: 15px; border-radius: 5px;">
         <p><strong>Generated URL:</strong></p>
         <code>/page/{{encode(pageName)}}/category/{{encode(category)}}</code>
      </div>
   </div>

   <script>
      var app = angular.module('directApp', []);
      app.controller('DirectController', function($scope) {
         $scope.pageName = 'Angular JS Tutorial';
         $scope.category = 'Web Development & Programming';
         
         $scope.encode = function(str) {
            return str ? encodeURIComponent(str) : '';
         };
      });
   </script>
</body>
</html>

The template dynamically generates encoded URLs as you modify the input values −

Generated URL: /page/Angular%20JS%20Tutorial/category/Web%20Development%20%26%20Programming

Common Use Cases

Following are common scenarios where encodeURIComponent() is used in AngularJS applications −

  • Query Parameters − Encoding search terms, user input, or form data before adding to URLs.

  • Dynamic Routing − Encoding route parameters that contain special characters or spaces.

  • API Endpoints − Encoding parameters before making HTTP requests to external APIs.

  • Social Media Sharing − Encoding URLs and text for social media sharing buttons.

Comparison

Method Best For Performance Reusability
Controller Function One-time encoding, button clicks Good Medium
Custom Filter Template expressions, repeated use Excellent High
Direct Expression Simple cases, dynamic generation Fair Low

Conclusion

The encodeURIComponent() function can be invoked in AngularJS templates through controller functions, custom filters, or direct expressions. Custom filters provide the best reusability and performance for template-based encoding, while controller functions work well for user-triggered encoding operations. Choose the method that best fits your application's architecture and use case requirements.

Updated on: 2026-03-16T21:38:53+05:30

543 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements