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();
},
}
}]);
由于某些原因,我想将模板的给定作用域编译为字符串,在询问了谷歌叔叔并做了一些实验后,我放弃了。
有人知道怎么做吗?也许我的方法根本就是错的?
我想注意到,作为结果,我需要模板编译成字符串,保存在一个变量中。
编辑更具体地说,我需要的是:
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);
}
}
}]);
虽然这与您的用例不完全相同,但所涉及的过程似乎是相同的。
相关文章:
- 字符串在将其传递给另一个活动Android JavaScript时读取Null
- 制作一个regex来验证只有一个数字的字符串
- 将html元素插入到文本字符串中,以匹配另一个html字符串
- NodeJS在一个较大的字符串中获取一个字符串的索引
- jquery从2个json字符串构建一个复选框表单
- 在Javascript中将一个值和字符串数组转换为if语句
- Javascript:用while循环在给定的count参数中重复一个字符串
- 如何使用另一个字符串作为模板从字符串中提取数据
- 用jQuery将字符串从一个类替换为另一个类
- 使用javascript或angularjs特定过滤器搜索字符串中第一个img标记的json值
- 如何检查一个字符串的所有字符是否都存在于另一个字符串中
- JavaScript:如何创建一个具有字符串名称的对象
- 如何从 javascript 中可能具有一个或多个图像的字符串中仅获取图像名称
- 在不使用循环的情况下,从一个数据库字符串值向javascript数组添加多个对象
- 从表单中动态生成一个字符串,传递给通过AJAX加载的PHP文件
- 当我JSON.stringfy(对象)时,我得到一个疯狂的字符串作为值
- 我可以使用JS一次使用JSON数组中的一个字符串吗
- 使用javascript替换字符串中除第一个和最后一个之外的所有字符
- 获取一个对象´s属性的名称使用字符串
- 删除一个“;从javascript中的字符串末尾