AngularJS编译并呈现从HTML文件code [英] AngularJS compile and render HTML code from file

查看:92
本文介绍了AngularJS编译并呈现从HTML文件code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有是我的自定义指令以下code:

There is the following code of my custom directive:

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 code。但它例如,在我的实际应用HTML code是更大的,我想从指令移动HTML code到模板。但是,我怎么能在这种情况下,模板编译HTML code?在此先感谢

So,as you can see, I render some HTML code using condition. But it's example, in my real application HTML code is much bigger, and I want to move HTML code from directive to template. But how can I compile HTML code from template in this case? Thanks in advance

推荐答案

一个指令定义对象可以有一个模板 templateUrl 属性。这两个可以是字符串函数返回一个字符串。如果定义 templateUrl 那么模板是从服务器(或模板缓存)获取。这就是你似乎什么想要的。

A directive definition object can have a template or a templateUrl property. Both can be either a String or a function that returns a String. If you define templateUrl then the template is fetched from the server (or the template cache). That's what you seem to want.

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();
     }
   };
 }

]); 

当有电流通过使用者然后模板被取出,编译和替换元件。有没有其他事情可做。

When there is a current user then the template is fetched, compiled and replaces the element. There is nothing else to do.

请注意,我用更换:真正的,这确实几乎一样 element.replaceWith 。这是pcated德$ P $,但不会到2.0角被删除。

Note that I used replace: true, which does almost the same as element.replaceWith. It's deprecated but won't be removed until Angular 2.0.

这篇关于AngularJS编译并呈现从HTML文件code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆