Angular:从一个字符串编译到另一个字符串

Angular: compiling template from string to string

本文关键字:字符串 一个 编译 另一个 Angular      更新时间:2023-09-26

看小提琴

test.directive('testMe', ['$compile', function($compile) {
          return {
            restrict: 'EA',
            transcluded: true,
            link: function(scope, element, attrs) {
              scope.state = 'compiled';
                //a = $(element.html());  //this gives: Error: Syntax error, unrecognized expression: Something I actually want to save {{state}}
                a = $('<div>' + element.html() + '</div>');
              var el = $compile(a)(scope);
              scope.compiled = element.html();
            },
          }
        }]);

由于某些原因,我想将模板的给定作用域编译为字符串,在询问了谷歌叔叔并做了一些实验后,我放弃了。

有人知道怎么做吗?也许我的方法根本就是错的?

我想注意到,作为结果,我需要模板编译成字符串,保存在一个变量中。

编辑

更具体地说,我需要的是:

var template = "<p>{{variable}}</p>";
$scope.variable = "test";
var compiled = //magic goes here
alert(compiled); // gives <p>test</p>

我最近偶然发现了一个类似的问题,几个小时后,我能够在这篇文章的一点帮助下解决它:来自Ben Lesh的博文

我想创建一个ComboBox来为另一个实体选择一个图像保存在关系数据库中。当然,我的实体也有其他关系,所以我在JSON-File

中描述了它们
//image
{ id: 4, path: 'http://www.example.com/myimage.png', name: 'Picture of my cat' }
//entity
{ id: 7, foo: 'bar', imageId: 4, anotherEntityId: 12}
//anotherEntity
{ id: 12, name: 'My Entity'}

我现在想创建一个用于输入新实体的公式,而对于外键,我想要一个组合框然后我声明了另一个JSON-Object,包含实体的每一列以及我希望它们如何呈现

{cols: 
    [
        {
         name: 'imageId', 
         displayName: 'Image', 
         type: Image, 
         template: '<img src="{{e.path}}" />{{e.name}}'
         },
         ...
]}
为了做到这一点,我创建了一个新的指令,叫做nComboBoxRenderer
<ng-combo-box-renderer data="image", template="column.template"></ng-combo-box-renderer>

directives.directive('ngComboBoxRenderer', ['$compile', function($compile) {
    return {
        restrict: "E",
        scope: {
            e: '=data',   // in my case this is the image
            template: '=template'  // the template
        },
        link: function($scope, element, attributes) {
            var tl = angular.element("<span>" + $scope.template + "</span>");
            compiled = $compile(tl);
            element.append(tl);
            compiled($scope);
        }
    }
}]);

虽然这与您的用例不完全相同,但所涉及的过程似乎是相同的。