javascript - Angular Directive - 在嵌入模板时替换标签

标签 javascript jquery angularjs templates angularjs-directive

我正在编写一个指令,它根据提供的属性采用模板。

Plnkr

JS

var app = angular.module('app', []);

app.directive('sample', function($compile){
  var a = '<div>template 1</div>';
  var b = '<div>template 2</div>';

  return {
    replace: true,
    restrict: 'E',
    scope: {
      type: '@'
    },
    link: function($scope, $element){
      var get_template = function(){
          if($scope.type == 'others'){
              return b;
          } else {
              return a;
          }
      };

      $($element).html(get_template()).show();
      $compile($($element).contents())($scope);
    }
  }
});

HTML

<sample></sample>
<sample type="others"></sample>

这里replace: true当我们在指令中提供模板属性时,它就可以工作。有什么办法可以摆脱<sample />标签,只需 <div /> .

还有另一种方法,

app.directive('sample', function($compile, $templateCache){
  var a = '<div>template 1</div>';
  var b = '<div>template 2</div>';

  $templateCache.put('template1.html', a);
  $templateCache.put('template2.html', b);

  return {
    template: '<div ng-include="get_template()" />',
    replace: true,
    restrict: 'E',
    scope: {
      type: '@'
    },
    link: function($scope, $element){
      var get_template = function(){
          if($scope.type == 'others'){
              return 'template2.html';
          } else {
              return 'template1.html';
          }
      };
    }
  }
});

但是上面的做法还是有<div ng-include />作为 <div>template1</div> 的父级而我只需要 <div>template .

有什么办法吗?

提前致谢。

最佳答案

您可以在 Angular 中使用restrict,将其限制为“A”并添加“sample”作为属性。

了解有关指令中限制的更多信息:AngularJS Directive Restrict A vs E

关于javascript - Angular Directive - 在嵌入模板时替换标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32879870/

相关文章:

javascript - 使用 Javascript 的图像加载触发器

javascript - 列过滤器不适用于行分组

javascript - 我不明白在 Controller 中使用 $inject

angularjs - eslint-plugin-Angular this.variable 导致没有方法 'findIndex'

javascript - jQuery - 获取多选列表中的所有项目

javascript - 使用 node-schedule 从 cron 返回值

javascript - 在 componentWillMount 内的函数内调用操作导致无法读取未定义的属性

jquery - MVC 同时返回 json 和 html 响应

jquery - 将一组复选框的选中状态复制到另一个字段集

javascript - AngularJS如何在依赖提供者的$http成功函数中设置变量