![](/img/trans.png)
[英]'Echo' html from string in angularjs when the string is on a template
[英]Generate HTML string from AngularJS template string
我有 angularjs 模板作为一个字符串,包括“ng-repeat”和其他指令。 我想在控制器中编译它以将结果 HTML 生成为字符串。
我想在 Angular 中应用的示例:
Input:
-------
var template = '<div ng-repeat="item in items">{{item.data}}</div>';
Output:
--------
var result = '<div>1</div><div>2</div><div>3</div><div>4</div>';
我希望在我使用的控制器中完成此操作,并尝试了以下操作:
var template = '<div ng-repeat="item in items">{{item.data}}</div>';
var linkFunction = $compile(template);
var result = linkFunction($scope);
console.log(result); // prints the template itself!
谢谢!
试一试:
var template = angular.element('<div ng-repeat="item in items">{{item.data}}</div>');
var linkFunction = $compile(template);
var result = linkFunction($scope);
$scope.$apply();
console.log(template.html());
为此,我之前为自己制定了一个指导性的几个项目:
angular.module('myApp')
.directive('ngHtmlCompile', ["$compile", function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(attrs.ngHtmlCompile, function (newValue, oldValue) {
element.html(newValue);
$compile(element.contents())(scope);
});
}
}
}]);
然后例如:
<div ng-html-compile='<div ng-repeat="item in items">{{item.data}}</div>'></div>
甚至字符串也可以是动态的:
<div ng-repeat="item in items" ng-html-compile="item.template">
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.