【发布时间】:2014-10-29 20:54:26
【问题描述】:
是否可以在没有 dom 的情况下获得已编译的 angular 指令 html-code?
这就是我想要的:
var scope = {
list: ["Peter","Paul","Mary"]
},
template = '<ul><li ng-repeat="item in list"{{item}}</li><ul>',
result;
result = desiredFunction( scope, template );
// result should be: "<ul><li>Peter</li><li>Paul</li><li>Mary</li></ul>"
有没有可能得到desiredFunction?
编辑:
为了让我的愿望更清楚一点:我想“编译”一个角度指令模板字符串不必将指令推送到 dom 中,因为我不想将它放在大教堂。反正我什至不想要一个指令。我只想要从模板字符串(template-string + scope-object ==> html-string)编译的字符串。
是否有任何 Angular 内部甚至外部(库)方式来做到这一点?
编辑(2):
接受 NewDev 的回答,更正我的 html 模板并添加 $timeout 导致我得到以下解决方案,该解决方案有效:
$scope.list = ["Peter", "Paul", "Mary"];
var template = '<ul><li ng-repeat="item in list">{{item}}</li></ul>';
var jqElem = angular.element(template);
$compile(jqElem)($scope);
$timeout( function() {
console.log( jqElem.html() );
});
编辑(3):
根据 zerflagL 的评论,这也是可能的(甚至更短):
$scope.list = ["Peter", "Paul", "Mary"];
var template = '<ul><li ng-repeat="item in list">{{item}}</li></ul>';
var result = $compile(template)($scope)[0];
$timeout( function() {
console.log( result );
});
【问题讨论】:
-
在链接函数中,你可以直接返回
element.html(),不是吗?我错过了什么吗? -
@NewDev 查看我的编辑。
标签: angularjs angularjs-directive