问题描述
我想创建一个名为,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个元素,和
By given links
to be array which has 2 elements, http://example.com/image.jpg and http://example.com/video.mp4
在链接
是图像的URL,这是,其结果必然是&LT; IMG SRC =http://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 =http://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
下面是一个
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);
}
}
}
};
});
这篇关于告诉指令,使用基于范围的变量不同的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!