【问题标题】:AngularJS compile and render HTML code from fileAngularJS 从文件中编译和渲染 HTML 代码
【发布时间】:2014-11-20 21:58:23
【问题描述】:

我的自定义指令有以下代码:

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 代码呢?提前致谢

【问题讨论】:

  • 你知道不用手动编译吧?
  • 是的,因为代码很大,我不想在指令中存储模板代码
  • 我的意思是你不必自己打电话给$compile,即使在你的例子中也是如此。这就是 template 属性的用途。因此,您可以使用templateUrl 从服务器获取 HTML。
  • @zeroflagL 你为什么不把它写成答案?

标签: javascript html angularjs


【解决方案1】:

指令定义对象可以具有template 或templateUrl 属性。两者都可以是String 或返回String 的function。如果您定义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 之前不会被删除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2013-05-31
    • 2013-11-12
    • 2019-07-27
    相关资源
    最近更新 更多