Reputation: 529
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>
By given links
to be array which has 2 elements, http://example.com/image.jpg and http://example.com/video.mp4
When link
is image url, which is http://example.com/image.jpg, the result would be <img src="http://example.com/image.jpg" />
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.
Please help.
Upvotes: 1
Views: 889
Reputation: 4773
you can do this in the link function just fine, all you will do is compile the video or img templates and append them
Here's a 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);
}
}
}
};
});
Upvotes: 1