您可以使用$compile传递指令进行处理,然后获取由Angular生成的HTML并以任何想要的方式处理它。但您还需要提供一个基于用户模型输入的唯一作用域,可以使用$rootScope.$new()来完成。在我的示例中,模型格式应为JSON,以避免出现错误,但如果您为自己的个人使用而制作此模型,则可以允许常规js输入并使用eval()函数,让用户编写更复杂的模型。
这是它的运行示例:http://jsbin.com/inocag/4/
JS
var module = angular.module('module', []);
module.directive('xxAngulizer', function($compile, $rootScope) {
return {
restrict: 'A',
template: '<div>TEMPLATE</div><textarea id="template" ng-model="template" ng-change="update"></textarea>' +
'<div>MODEL</div><textarea id="model" ng-model="model" ng-change="update"></textarea>' +
'<div>HTML OUTPUT</div><textarea id="output" ng-model="output"></textarea>' +
'<div id="hidden" ng-hide="true"></div>',
scope: true,
link: function($scope, elem) {
var templateElem = $(elem.find('#template'));
var modelElem = $(elem.find('#model'));
var outputElem = $(elem.find('#output'));
var hiddenElem = $(elem.find('#hidden'));
$scope.template = '<div ng-repeat="cat in cats">{{cat.name}} the famous {{cat.breed}}</div>';
$scope.model = '{ "cats": [{ "name": "Fussy", "breed": "Russian Blue" },' +
' { "name": "Juniper", "breed": "Maine Coon" },' +
' { "name": "Chives", "breed": "Domestic Shorthair" }] }';
$scope.output = '';
$scope.update = update;
var $magicScope;
function update() {
var model, template;
try {
model = JSON.parse($scope.model);
} catch (err) {
model = null;
$scope.output = 'Model is not valid JSON.';
}
if (model) {
try {
template = $($scope.template);
} catch (err) {
console.log(err);
template = null;
$scope.output = 'Template is not valid(ish) HTML.';
}
}
if (template) {
if ($magicScope) { $magicScope.$destroy(); }
$magicScope = $rootScope.$new(true);
for (var p in model) {
$magicScope[p] = model[p];
}
$compile(hiddenElem.html(template))($magicScope);
setTimeout(function(){
$scope.output = hiddenElem.html();
$scope.$apply();
}, 500);
}
}
$scope.$watch('template', update);
$scope.$watch('model', update);
setTimeout(update, 500);
}
};
});
HTML
<!DOCTYPE html>
<html>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
<body ng-app="module">
<div xx-angulizer></div>
</body>
</html>
这很有趣,我在回答过程中实际上学到了不少东西!