【问题标题】:Tell directive to using different template based on scope variable告诉指令根据范围变量使用不同的模板
【发布时间】:2014-11-06 07:14:38
【问题描述】:

我想创建一个名为 tagFor 的指令,例如,它根据通过属性传递的数据生成适当的指令。

<tag-for source="{{link}} ng-repeat="link in links"></tag-for>

通过给定links 为具有2 个元素的数组,http://example.com/image.jpghttp://example.com/video.mp4

link是图片的url,也就是http://example.com/image.jpg,结果就是&lt;img src="http://example.com/image.jpg" /&gt;

但当link 是视频网址时,结果将是&lt;video width="320" height="240" controls&gt;&lt;source src="http://example.com/video.mp4" type="video/mp4"&gt;&lt;/video&gt;

我尝试在指令中使用compile 函数,但我无法获得link 的值来告诉指令返回适当的模板。

请帮忙。

【问题讨论】:

  • 你应该看看ng-include,它可以帮助你。

标签: angularjs


【解决方案1】:

你可以在链接功能中做到这一点,你所要做的就是编译视频或img模板并附加它们

这是Plunker

app.directive('tagFor', function($compile, $timeout) {

  var video = '<iframe width="340" height="280" frameborder="0" allowfullscreen></iframe>';
  var image = '<div><img ng-src="{{link.url}}" width="340" height="280"/></div>';

  return {
    restrict: 'EA',
    scope: {
      link: '=ngModel'
    },
    template: '<div>{{link.type}}</div>',
    transclude: true,

    compile: function(tElem, tAttr) {
      //this is just the link func
      return function(scope, el, attr, ctrl, trans) {
        if (scope.link.type == 'video') {
          var vid = $compile(video)(scope);
          el.append(vid);    
        } else if (scope.link.type == 'image') {
          var img = $compile(image)(scope);
          el.append(img);
        }

      }
    }

  };

});

【讨论】:

  • 非常适合$compile 函数
猜你喜欢
  • 1970-01-01
  • 2015-01-03
  • 2014-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多