2014-03-13 85 views
1

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

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

+0

该文档似乎没有提及'$ eval'的任何地方。您应该直接'编译'模板并为其提供创建'element'的范围,除非您通过'attrs'元素获取该字符串,否则您不需要任何'$ eval'。 –

+0

@musically_ut我更新了我的问题,以表明我正在使用的示例。如果我不评估,那么在span标签中的任何角度表达式都会被显示,因为它没有先评估它。我希望角度表达式(如果有的话)在我编译之前进行评估。 – callmekatootie

回答

4

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

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

+0

如何将编译好的模板添加到元素中?我的意思是,在执行'$ compile'后,我希望将编译后的模板添加到DOM中的特定位置 - 我该怎么做? – callmekatootie

+0

没关系,我得到了关于添加编译模板[这里]的答案(http://stackoverflow.com/questions/14846836/insert-an-angular-js-template-string-inside-an-element)。感谢您的回答。 – callmekatootie