【发布时间】:2014-03-13 17:11:28
【问题描述】:
我有一个简单的字符串如下:
var templateString = "<span>This is a test</span>"
此字符串在指令的 link 函数中定义。
现在,在link 函数中,我执行以下代码:
scope.$eval(templateString);
我的下一步是$compile 数据并将其与范围相关联。
但是,当我执行 $eval 时出现错误:
Uncaught Error: Syntax Error: Token 'span' is an unexpected token at
column 2 of the expression [<span>This is a test</span>]
starting at [span>This is a Test</span>].
但是,如果我查看位于 here 的文档,我似乎已经正确执行了这些步骤,但字符串没有评估。
编辑:我正在使用文档中的以下示例:
angular.module('compile', [], function($compileProvider) {
// configure new 'compile' directive by passing a directive
// factory function. The factory function injects the '$compile'
$compileProvider.directive('compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
})
});
我没有使用$watch,但是因为我不需要观看任何表达式并且已经拥有模板(templateString)。
【问题讨论】:
-
文档似乎没有在任何地方提到
$eval。您应该直接$compile模板并为其提供创建element的范围,除非您通过元素attrs获取该字符串,否则您不需要任何$eval。 -
@musically_ut 我更新了我的问题以表明我正在使用的示例。如果我不进行评估,那么
span标记中的任何角度表达式都会按原样显示而不先评估它......我希望在编译之前也评估角度表达式(如果有的话)。
标签: angularjs angularjs-compile