告诉指令,使用基于范围的变量不同的模板 [英] Tell directive to using different template based on scope variable

查看:133
本文介绍了告诉指令,使用基于范围的变量不同的模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个名为,tagFor指令的基础上,通过属性传递的数据能产生适当的,例如。

I want to create a directive called, tagFor, which generate appropriate based on data that passed through attribute, for example.

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

由下式给出链接是数组里面有2个元素, http://example.com/image.jpg http://example.com/video.mp4

By given links to be array which has 2 elements, http://example.com/image.jpg and http://example.com/video.mp4

链接是图像的URL,这是的http:/ /example.com/image.jpg ,其结果必然是&LT; IMG SRC =htt​​p://example.com/image.jpg/&GT;

When link is image url, which is http://example.com/image.jpg, the result would be <img src="http://example.com/image.jpg" />

但是,当链接是一个视频网址,结果将是&lt;视频WIDTH =320HEIGHT =240控制&GT;&LT ;源SRC =htt​​p://example.com/video.mp4TYPE =视频/ MP4&GT;&LT; /视频&GT;

But when link is a video url, the result would be <video width="320" height="240" controls><source src="http://example.com/video.mp4" type="video/mp4"></video>

我尝试使用编译指令的功能,但我不能让链接来告诉指令返回适当的值模板。

I try to use compile function in directive but I cannot get value of link to tell directive to return appropriate template.

请帮忙。

推荐答案

您可以在链接功能做到这一点就好了,你要做的是编译视频或IMG模板,其中追加

you can do this in the link function just fine, all you will do is compile the video or img templates and append them

下面是一个 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);
        }

      }
    }

  };

});

这篇关于告诉指令,使用基于范围的变量不同的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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