2014-11-06 42 views
1

我想创建一个名为tagFor的指令,例如,它基于通过属性的数据生成适当的指令。Tell指令根据范围变量使用不同的模板

<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,其结果将是<img src="http://example.com/image.jpg" />

但当link是视频url,结果会是<video width="320" height="240" controls><source src="http://example.com/video.mp4" type="video/mp4"></video>

我试着用compile函数在di rective但我不能得到link的价值告诉指令返回适当的模板。

请帮忙。

+0

你应该看看'NG-包括',它可以帮助你。 – Chandermani 2014-11-06 07:36:03

回答

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); 
     } 

     } 
    } 

    }; 

}); 
+0

非常适合'$ compile'功能 – Stackle 2014-11-06 09:53:31