javascript - Angular : compiling template from string to string

标签 javascript angularjs templates compilation

See the fiddle

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();
            },
          }
        }]);

出于某种原因,我想将给定范围的模板编译为字符串,在询问了 Uncle Google 并做了一些实验后,我放弃了。

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

我想注意到,因此我需要将模板编译为字符串,保存在变量中。

编辑

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

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

最佳答案

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

我想创建一个组合框来选择另一个实体的图像以保存在关系数据库中。当然,我的实体也有其他关系,因此我在 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}}'
         },
         ...
]}

为此,我创建了一个名为 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);
        }
    }
}]);

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

关于javascript - Angular : compiling template from string to string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22356678/

相关文章:

php - 通过 jQuery 向 PHP 发送/接收数据

javascript - Angularjs 1.x Controller 在指令中没有响应

javascript - AngularJs $q.defer() 不工作

javascript - angularjs.检查表格中是否至少选中了一个复选框

javascript - Ajax 调用。将值传递给另一个 php 文件

c++ - 为什么这个模板函数调用在这个函数内部不起作用?

javascript - 在 grunt browserify 中使用下划线模板

c++ - 初始化自定义数组类而不创建拷贝

angularjs - Protractor - 由于有关 “RangeError: Maximum call stack size exceeded” 的错误,无法期待 Toast 通知

javascript - 当我的应用程序注销时如何完全清除 $rootScope