javascript - AngularJS $从 templateURL 编译 HTML

标签 javascript angularjs angularjs-directive

在AngularJS中动态添加HTML有如下方法

   var template = '<div>{{value}}</div>';
   var element = angular.element(template);
   placeholder.replaceWith(element);
   $compile(element)($scope);

是否可以从 templateURL 或单独加载模板执行相同的操作? (使用标准机制,使其缓存在 $templateCache 中)

最佳答案

当然,您只需使用 $http 服务来获取模板,然后手动编译和插入它。 $http 服务将隐式处理缓存。

PLUNKER

(最简单的)指令:

app.directive('message', [
  '$http',
  '$compile',
  function($http, $compile) {
    var tpl = "template.html";

    return {
      scope: true,
      link: function(scope, element, attrs){
        scope.message = attrs.message;

        $http.get(tpl)
          .then(function(response){
            element.html($compile(response.data)(scope));
          });
      }
    };

  }
]);

查看:

<span message="Hi World!"></span>
<span message="My name is Angular."></span>

指令模板(template.html):

<span>{{message}}</span>

关于javascript - AngularJS $从 templateURL 编译 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21223961/

相关文章:

javascript - AngularJS 指令 : get restrict type in link phase

javascript - 防止歌剧鼠标手势

java - 我需要帮助将对象代码从 JavaScript 翻译为 Java

javascript - Angular JS : Filter using textbox and Checkbox

javascript - HTML5 Canvas : How do I merge 2 canvas into 1 (of which 1 is draggable)

javascript - Angular.js - 在指令中设置 ng-pattern 时 ngModel 值未定义

javascript - 单击外部时关闭 Bootstrap 弹出窗口

Javascript 更新进度条,然后切换可见的 div

javascript - 严格模式 -> 更改了 Controller 结构,在 For In 循环中获取 'key is not defined'

javascript - ngTouch 的 ngClick 阻止复选框和视频在大多数移动设备上工作