首页 > 文章列表 > 如何在AngularJS模板中调用encodeURIComponent?

如何在AngularJS模板中调用encodeURIComponent?

angularjs 调用 模板 encodeURIComponent
310 2023-09-17

在本文中,我们将学习如何从 HTML 中的 angularjs 模板调用编码 URI 组件。

每当某个字符出现在 URI 中时,encodeURIComponent() 函数就会将其替换为一个、两个、三个或四个表示该字符的 UTF-8 编码的转义序列(只能是由两个“代理”字符组成的字符的四个转义序列)。

语法

以下是encodeURIComponent的语法

encodeURIComponent(uriComponent)

Uri组件

任何对象,包括字符串、数字、布尔值、null 或未定义。 uriComponent在编码之前转换为字符串。

让我们看一下以下示例以更好地理解。

示例 1

在下面的示例中,我们使用encodeURI组件

<!DOCTYPE html>
<html>
<body>
   <p id="tutorial"></p>
   <script>
      let uri = "https://www.tutorialspoint.com/index.htm";
      let encoded = encodeURIComponent(uri);
      document.getElementById("tutorial").innerHTML = encoded;
   </script>
</body>
</html>

运行上述脚本时,会弹出输出窗口,显示我们在上述脚本中使用的 URL 的编码 URL。

示例 2

在下面的示例中,我们使用函数 encodeURIcomponent(string) 对 url 参数进行编码。

<!DOCTYPE html>
<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
   <script>
      var myApp = angular.module("mytutorials", []);
      myApp.controller("mytutorials1", function($scope) {
         $scope.url1 = 'https://www.tutorialspoint.com/index.htm';
         $scope.url2 = '';
         $scope.encodeUrlStr = function() {
            $scope.url2 = encodeURIComponent($scope.url1);
         }
      });
   </script>
</head>
<body>
   <div ng-app="mytutorials">
      <div ng-controller="mytutorials1">
         <button ng-click ="encodeUrlStr()" >Encode URL</button>
         <br>
         URL1 = {{url1}}<br>
         URL2 = {{url2}}
      </div>
   </div>
</body>
</html>

当脚本执行时,它将生成由 url1 和 url2 组成的输出,该输出为空,并在网页上显示一个encodeURL 按钮。

如果用户点击encodeURL按钮,url1中给出的url将被编码并显示在url2中。