【问题标题】:Unable to perform $scope.$eval无法执行 $scope.$eval
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 如何将编译好的模板添加到元素中?我的意思是,在执行$compile 之后,我希望将编译后的模板添加到 DOM 中的特定位置 - 我该怎么做?
  • 没关系,我得到了关于添加编译模板 here 的答案。谢谢你的回答。
猜你喜欢
  • 1970-01-01
  • 2017-05-09
  • 1970-01-01
  • 2016-05-24
  • 1970-01-01
  • 1970-01-01
  • 2017-05-15
  • 1970-01-01
  • 2020-10-16
相关资源
最近更新 更多