Angularjs 无法执行$scope.$eval
我有一个简单的字符串,如下所示:Angularjs 无法执行$scope.$eval,angularjs,angularjs-compile,Angularjs,Angularjs Compile,我有一个简单的字符串,如下所示: var templateString = "<span>This is a test</span>" 我的下一步是编译数据并将其与范围关联 但是,我在执行$eval时出现错误: 但是,我不使用$watch,因为我不需要查看任何表达式,并且模板已经包含在templateString中。$eval用于计算表达式,您的templateString不是有效的表达式,这就是发生错误的原因 您应该只使用$compiletemplateStrings
var templateString = "<span>This is a test</span>"
我的下一步是编译数据并将其与范围关联
但是,我在执行$eval时出现错误:
但是,我不使用$watch,因为我不需要查看任何表达式,并且模板已经包含在templateString中。$eval用于计算表达式,您的templateString不是有效的表达式,这就是发生错误的原因
您应该只使用$compiletemplateStringscope,它将编译您的模板,并与scope链接,这意味着所有表达式都将使用提供的作用域求值。$eval用于计算表达式,您的templateString不是有效的表达式,这就是发生错误的原因
您应该只使用$compiletemplateStringscope,它将编译您的模板,并与scope链接,这意味着所有表达式都将使用提供的作用域进行计算。文档似乎没有在任何地方提到$eval。您应该直接$compile模板并为其提供创建元素的作用域,您不需要任何$eval,除非您是通过元素属性获取该字符串。@musical\u ut我更新了我的问题,以指示我正在使用的示例。如果我不求值,那么span标记中的任何角度表达式都会按原样显示,而不会先求值。。。我希望在编译之前也计算角度表达式(如果有的话)。文档中似乎没有提到$eval。您应该直接$compile模板并为其提供创建元素的作用域,您不需要任何$eval,除非您是通过元素属性获取该字符串。@musical\u ut我更新了我的问题,以指示我正在使用的示例。如果我不求值,那么span标记中的任何角度表达式都会按原样显示,而不会先求值。。。我希望在编译之前也计算角度表达式(如果有的话)。如何将编译后的模板添加到元素中?我的意思是,在执行$compile之后,我希望将编译后的模板添加到DOM中的特定位置-我该怎么做?不管怎样,我得到了关于添加编译后的模板的答案。谢谢您的回答。如何将编译后的模板添加到元素中?我的意思是,在执行$compile之后,我希望将编译后的模板添加到DOM中的特定位置-我该怎么做?不管怎样,我得到了关于添加编译后的模板的答案。谢谢你的回答。
scope.$eval(templateString);
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>].
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);
}
);
};
})
});