[英]AngularJS compile and render HTML code from file
我的自定义指令有以下代码:
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代码? 提前致谢
指令定义对象可以具有template
或templateUrl
属性。 两者都可以是String
或返回String
的function
。 如果定义templateUrl
则将从服务器(或模板缓存)中获取模板。 那就是你想要的。
angular.module('app.directives', []).directive('userHeader', ['authService', '$compile', function(authService, $compile) {
var loggedInUrl = '...';
var notLoggedInUrl = '...';
return {
restrict: 'AEC',
templateUrl: function() {
if (authService.currentUser()) {
return loggedInUrl;
} else {
return notLoggedInUrl;
}
},
replace: true,
link: function(scope, elem, attrs) {
scope.user = authService.currentUser();
}
};
}
]);
如果当前有用户,则将获取,编译并替换模板的模板。 没有其他事情可做。
请注意,我使用了replace: true
,它与element.replaceWith
几乎一样。 它已被弃用,但直到Angular 2.0才将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.