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

Javascript Angular:从一个字符串到另一个字符串编译模板,javascript,angularjs,templates,compilation,Javascript,Angularjs,Templates,Compilation,test.directive('testMe',['$compile',function($compile){ 返回{ 限制:“EA”, 是的, 链接:函数(范围、元素、属性){ scope.state='compiled'; //a=$(element.html());//这给出了:错误:语法错误,无法识别的表达式:我实际上想要保存的东西{{state} a=$(''+元素.html()+''); 变量el=$compile(a)(范围); scope.compiled=element.htm

test.directive('testMe',['$compile',function($compile){
返回{
限制:“EA”,
是的,
链接:函数(范围、元素、属性){
scope.state='compiled';
//a=$(element.html());//这给出了:错误:语法错误,无法识别的表达式:我实际上想要保存的东西{{state}
a=$(''+元素.html()+'');
变量el=$compile(a)(范围);
scope.compiled=element.html();
},
}
}]);
出于某种原因,我想将给定范围的模板编译成字符串,在询问了谷歌叔叔并做了一些实验后,我放弃了

安尼欧知道怎么做吗?也许我的方法是错误的

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

编辑

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

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

”; $scope.variable=“测试”; var compiled=//这里有魔术 警报(已编译);//进行检验


我最近偶然发现了一个类似的问题,几个小时后,我在这篇文章的帮助下解决了这个问题:

我想创建一个组合框,为另一个实体选择一个要保存在关系数据库中的图像。当然,我的实体也有其他关系,所以我在JSON文件中描述了它们

//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对象,它包含实体的每一列,以及我希望它们的呈现方式

{cols: 
    [
        {
         name: 'imageId', 
         displayName: 'Image', 
         type: Image, 
         template: '<img src="{{e.path}}" />{{e.name}}'
         },
         ...
]}
{cols:
[
{
名称:“imageId”,
displayName:'图像',
类型:图像,
模板:“{e.name}”
},
...
]}
为此,我创建了一个名为ncomboxRenderer的新指令

<ng-combo-box-renderer data="image", template="column.template"></ng-combo-box-renderer>

-

指令('ngComboBoxRenderer',['$compile',函数($compile){ 返回{ 限制:“E”, 范围:{ e:'=data',//在我的例子中,这是图像 模板:'=template'//模板 }, 链接:函数($范围、元素、属性){ var tl=angular.element(“+$scope.template+”); compiled=$compile(tl); 元素追加(tl); 汇编($范围); } } }]);
虽然这与您的用例不完全相同,但所涉及的过程似乎是相同的。

您到底想做什么?由于您使用的是
link
函数,指令已经编译好了,所以再次编译它是没有意义的,正如我刚才所说的,我想将编译好的模板保存到一个字符串中。我要去的地方没有关系,因为我在很多地方都试着去做。。。事实上,我甚至试图:'result=$compile(angular.element(“zsfgsdfg{{variable}}

”)($scope);'但仍然没有结果。我现在明白了,所以也许你想使用类似于
$parse('variable')($scope)
的东西。不幸的是,这不是我需要的——据我所知,$parse编译表达式,而我需要编译整个模板。我更新了我的小提琴来检查它是如何工作的,不幸的是,它绝对不是我需要的。
<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);
        }
    }
}]);