AngularJS – ngHref 指令


AngularJS 中的ngHref 指令解決了連結斷開時替換標記的問題,從而導致系統返回 404 錯誤。我們不應在href 屬性中使用像{{hash}}這樣的標記,它會更改或替換標記值,而應使用ngHref 指令,因為該連結可能會斷開,從而導致返回 System Error。

語法

<element ng-href="expression">..content..</element>

示例 - ngHref 指令

在 Angular 專案目錄中建立一個 "ngHref.html" 檔案,並複製貼上以下程式碼片段。

<!DOCTYPE html>
<html>
   <head>
      <title>ngHref Directive</title>

      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">             </script>
   </head>

   <body ng-app="" style="text-align: center;">
      <h1 style="color: green;">
         Welcome to Tutorials Point
      </h1>
      <h2>
         AngularJS | ngHref Directive
      </h2>
      <div ng-init="url ='https://tutorialspoint.tw/index.htm'">
         <p>Go to <a ng-href="{{url}}">TutorialsPoint</a></p>
      </div>
   </body>
</html>

輸出

要執行以上程式碼,只需轉到檔案並像普通 HTML 檔案一樣執行它。

示例 2

在 Angular 專案目錄中建立一個 "ngHref.html" 檔案,並複製貼上以下程式碼片段。

<!DOCTYPE html>
<html>
   <head>
      <title>ngHref Directive</title>

      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">      </script>
   </head>

   <body ng-app="" style="text-align: center;">
      <h1 style="color: green;">
         Welcome to Tutorials Point
      </h1>
      <h2>
         AngularJS | ngHref Directive
      </h2>
      <input ng-model="value" /><br />
      <a id="link-1" href ng-click="value = 1">link 1</a> (link, This link will not reload)<br/>
      <a id="link-2" href="" ng-click="value = 2">link 2</a> (link,This link will not reload)<br />
      <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, Thislink will reload!)<br />
      <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (nolink)<br />
      <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
   </body>
</html>

輸出

要執行以上程式碼,只需轉到檔案並像普通 HTML 檔案一樣執行它。您將在瀏覽器視窗中看到以下輸出。

更新於:08-Oct-2021

235 瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.