我有一个非常简化的版本,我正在做的事情可以解决问题.
我有一个简单的directive.每当您单击一个元素时,它会添加另一个元素.但是,需要首先编译它才能正确呈现它.
我的研究引导我$compile.但是所有的例子都使用了一个复杂的结构,我真的不知道如何在这里应用.
小提琴在这里:http://jsfiddle.net/paulocoelho/fBjbP/1/
JS就在这里:
var module = angular.module('testApp', [])
.directive('test', function () {
return {
restrict: 'E',
template: '<p>{{text}}</p>',
scope: {
text: '@text'
},
link:function(scope,element){
$( element ).click(function(){
// TODO: This does not do what it's supposed to :(
$(this).parent().append("<test text='n'></test>");
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
Josh David Miller的解决方案:http: //jsfiddle.net/paulocoelho/fBjbP/2/
我有许多角度1.5组件,都采用相同的属性和数据结构.我认为它们可以重新考虑到单个组件中,但我需要一种基于type属性的插值来动态选择模板的方法.
var myComponentDef = {
bindings: {
type: '<'
},
templateUrl: // This should be dynamic based on interpolated type value
};
angular.module('myModule').component('myComponent', myComponentDef);
Run Code Online (Sandbox Code Playgroud)
我不能使用,templateUrl function($element, $attrs) {}因为它中的值$attrs是非插值的,所以我不会得到传入数据中指定的类型.
我可以只有一个带有一系列ng-if或ng-switch指令的大模板,但我想将模板分开.
或者,我可以将组件分开并ng-switch在父组件中使用等,但我不喜欢这样,因为它看起来像是很多重复.
我正在寻找一种解决方案,我可以使用插入type传递到绑定中的插值来匹配每种类型的模板URL,然后将用于构建组件.
这可能吗?
谢谢