【发布时间】:2014-11-20 21:58:23
【问题描述】:
我的自定义指令有以下代码:
angular.module('app.directives', []).directive('userHeader', ['authService', '$compile', function(authService, $compile) {
return {
restrict: 'AEC',
link: function(scope, elem, attrs) {
var html;
if (authService.currentUser()) {
html = $compile("<h1>You successfully entered, dear {{ user.name }}!</h1>")(scope);
elem.replaceWith(html);
} else {
html = $compile("<h1>You didn't enter</h1>")(scope);
elem.replaceWith(html);
}
return scope.user = authService.currentUser();
}
};
}
]);
所以,如您所见,我使用条件渲染了一些 HTML 代码。但这是示例,在我的实际应用程序中 HTML 代码要大得多,我想将 HTML 代码从指令移动到模板。但是在这种情况下如何从模板编译 HTML 代码呢?提前致谢
【问题讨论】:
-
你知道不用手动编译吧?
-
是的,因为代码很大,我不想在指令中存储模板代码
-
我的意思是你不必自己打电话给
$compile,即使在你的例子中也是如此。这就是template属性的用途。因此,您可以使用templateUrl从服务器获取 HTML。 -
@zeroflagL 你为什么不把它写成答案?
标签: javascript html angularjs