我将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!
谢谢!
答案 0 :(得分:7)
给它一个旋转:
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());
答案 1 :(得分:4)
为此目的,我在几个项目前做了一个指令:
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>