无法执行$ scope。$ eval

时间:2014-03-13 17:11:28

标签: angularjs angularjs-compile

我有一个简单的字符串如下:

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)。

1 个答案:

答案 0 :(得分:4)

$eval是评估一个表达式,你的templateString不是一个有效的表达式,这就是错误发生的原因。

您应该只使用$compile(templateString)(scope),它将编译您的模板,与范围链接,意味着将使用提供的范围评估所有表达式。

相关问题