告诉指令,使用基于范围的变量不同的模板变量、指令、范围、模板

由网友(尘&墨く)分享简介:我想创建一个名为,tagFor指令的基础上,通过属性传递的数据能产生适当的,例如。I want to create a directive called, tagFor, which generate appropriate based on data that passed through attribute, f...

我想创建一个名为,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 https://p.xsw88.cn/allimgs/daicuo/20230913/1188.png.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="https://p.xsw88.cn/allimgs/daicuo/20230913/1187.png.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);
        }

      }
    }

  };

});
阅读全文

相关推荐

最新文章