簡體   English   中英

AngularJS編譯並渲染文件中的HTML代碼

[英]AngularJS compile and render HTML code from file

我的自定義指令有以下代碼:

angular.module('app.directives', []).directive('userHeader', ['authService', '$compile', function(authService, $compile) {
  return {
    restrict: 'AEC',
      link: function(scope, elem, attrs) {
        var html;
        if (authService.currentUser()) {
          html = $compile("<h1>You successfully entered, dear {{ user.name }}!</h1>")(scope);
          elem.replaceWith(html);
        } else {
          html = $compile("<h1>You didn't enter</h1>")(scope);
          elem.replaceWith(html);
        }

        return scope.user = authService.currentUser();
      }
    };
  }
]); 

因此,如您所見,我使用條件渲染了一些HTML代碼。 但這是一個例子,在我的實際應用程序中,HTML代碼更大,並且我想將HTML代碼從指令移動到模板。 但是在這種情況下,如何從模板編譯HTML代碼? 提前致謝

指令定義對象可以具有templatetemplateUrl屬性。 兩者都可以是String或返回Stringfunction 如果定義templateUrl則將從服務器(或模板緩存)中獲取模板。 那就是你想要的。

angular.module('app.directives', []).directive('userHeader', ['authService', '$compile',      function(authService, $compile) {
 var loggedInUrl = '...';
 var notLoggedInUrl = '...';

 return {
   restrict: 'AEC',
     templateUrl: function() {
       if (authService.currentUser()) {
         return loggedInUrl;
       } else {
         return notLoggedInUrl;
       }
     }, 
     replace: true,
     link: function(scope, elem, attrs) {
       scope.user = authService.currentUser();
     }
   };
 }

]); 

如果當前有用戶,則將獲取,編譯並替換模板的模板。 沒有其他事情可做。

請注意,我使用了replace: true ,它與element.replaceWith幾乎一樣。 它已被棄用,但直到Angular 2.0才將其刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM