2014-11-06 67 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