Angularjs 基于条件在循环中添加指令
我有一个timeline.json,类似于:Angularjs 基于条件在循环中添加指令,angularjs,angularjs-directive,angularjs-ng-repeat,Angularjs,Angularjs Directive,Angularjs Ng Repeat,我有一个timeline.json,类似于: [{ "from":"twitter", //... }, { "from": "facebook" //... }] 基于from属性,我需要“呈现”特定指令:在循环中发布twitter或facebook 我该怎么做呢?您可以创建一个指令,根据传递的参数编译所需的指令 比如: .directive('renderOther', function($compile) { return { restrict: 'E', s
[{
"from":"twitter",
//...
},
{
"from": "facebook"
//...
}]
基于from
属性,我需要“呈现”特定指令:在循环中发布twitter或facebook
我该怎么做呢?您可以创建一个指令,根据传递的参数编译所需的指令 比如:
.directive('renderOther', function($compile) {
return {
restrict: 'E',
scope: {
type: '='
},
link: functtion(scope, elem, attrs) {
var dir = $('<post-' + scope.type + '></post-'+scope.type+'>');
dir.appendTo(elem);
$compile(elem.contents())(scope);
}
}
});
指令('renderOther',函数($compile){
返回{
限制:'E',
范围:{
类型:'='
},
链接:函数(作用域、元素、属性){
var dir=$('');
附录董事(elem);
$compile(elem.contents())(范围);
}
}
});
Html:
(它不是工作代码-只是一个想法)有几种方法。您可以在链接阶段使用ng开关、ng if或自定义处理程序函数。您可以在文档中找到更多信息 基本上,在基于条件语句调用指令的标记之间切换,即模型中的“from”值。例如,您可以将ng if指令与ng include结合使用,以基于此条件呈现模板的一部分。只要确保它不会降低性能
<div ng-repeat="i in items">
<render-other type="i.from"></render-other>
</div>