我不知道的建立必将对属性值的指令的一种方式,但也许你可以看看这个以前的SO回答:Custom Input Types
的想法是创建根据不同的模板使用指令的编译函数将其转换为属性的值。您可以在开始时放入所有自定义输入模板(不是必需的)。
angular.module('myapp', ['myapp.directives'])
.run(['$http', '$templateCache', function($http, $templateCache) {
$templateCache.put('span.html', '<span>text</span>');
$http.get('back_button.html', {cache:$templateCache});
}]);
并从缓存检索输入模板根据所述类型属性:
angular.module('myapp.directives', [])
.directive('ui', ['$templateCache', function($templateCache) {
return {
restrict: 'E',
compile: function(elem, attrs)
{
var type = attrs.type || 'span.html'; // default value ?
elem.replaceWith($templateCache.get(type));
}
}
}]);
此代码未测试。
编辑:这也可以工作,我认为,使用带有$链接功能编译,不预压模板,但仍缓存他们:
angular.module('myapp.directives', [])
.directive('ui', ['$http', '$templateCache', '$compile', function($http, $templateCache, $compile) {
return {
restrict: 'E',
link: function(scope, elem, attrs)
{
var type = attrs.type || 'span.html'; // default value ?
$http.get('views/' + type + '.html', {cache: $templateCache}).then(function(result) {
elem.replaceWith($compile(result.data)(scope));
});
}
}
}]);
此代码为我工作。
很好的答案。我尝试了类似的东西,但不是使用编译函数,而是使用链接函数将类型添加为应该触发第二个指令的CSS类。任何想法为什么它从不运行第二个指令? [小提琴](http://jsfiddle.net/yxFrN/) – mfelix 2013-04-10 20:07:33
很难说 - 你记得包括[$ compile](http://docs.angularjs.org/api/ng.$compile)服务和在添加CSS类后重新编译元素?你可以阅读更多关于编译过程[这里](http://docs.angularjs.org/guide/directive)。如果你可以在[plnkr](http://plnkr.co)上创建一个例子,我可以看看 – joakimbl 2013-04-10 21:35:44
我在上面的评论中放了一个小提琴链接;也许你没有看到它?我会阅读$ compile,谢谢。 – mfelix 2013-04-10 22:39:55