Angular:从字符串到字符串的编译模板 [英] Angular: compiling template from string to string
问题描述
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();
},
}
}]);
由于某种原因,我想编译一个给定范围的模板到一个字符串,并做了一些我放弃的实验。
For some reason I want to compile template with a given scope to a string, and after asking Uncle Google and doing some experiments I gave up.
annyone知道如何做到这一点吗?也许我的做法是错误的?
Does annyone knows how to do this? Maybe my approach is wrong at all?
我想注意,因此我需要模板编译为字符串,保存在一个变量。
I want to notice that as a result I need template compiled to string, saved in a variable.
EDIT
更具体来说,这里是我需要的:
To be more specific, here's what i need:
var template = "<p>{{variable}}</p>";
$scope.variable = "test";
var compiled = //magic goes here
alert(compiled); // gives <p>test</p>
推荐答案
我最近偶然发现了一个类似的问题,我能够解决它与这篇文章一点帮助:
Ben Lesh的博客帖子
I recently stumbled onto a similar problem and after several hours i was able to solve it with a little help from this post: Blog post from Ben Lesh
我想创建一个ComboBox来为另一个实体选择一个图像在关系数据库中。当然我的实体也有其他关系,所以我在一个JSON文件描述他们。
I wanted to create a ComboBox to select an Image for another Entity to save in a relational Database. Of course my Entity had other relations too and so I described them in a 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'}
我现在想创建一个Formular用于输入新实体,对于外键我想要一个combobox
然后我声明另一个JSON对象,包含实体的每一列
I now wanted to create a Formular for entering new entities and for the foreign keys I wanted a combobox I then declared another JSON-Object, containing every column of entity and also how i wanted them rendered
{cols:
[
{
name: 'imageId',
displayName: 'Image',
type: Image,
template: '<img src="{{e.path}}" />{{e.name}}'
},
...
]}
为此,我创建了一个新的指令,名为nComboBoxRenderer
To do so i created a new directive, called 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);
}
}
}]);
虽然这不是你所用的完全相同的用例,但涉及的过程看起来是一样的。
While this is not the exact same use case as you have, the process involved appears to be the same.
这篇关于Angular:从字符串到字符串的编译模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!