【问题标题】:AngularJS $interpolate error text.indexOf while compiling template编译模板时AngularJS $interpolate错误text.indexOf
【发布时间】:2016-02-24 08:25:50
【问题描述】:

我正在尝试在 AngularJS 的服务中编译模板,但在使用 $compile 服务时不断收到此错误:

text.indexOf is not a function

我尝试了几种不同的方法,但似乎无法找到可行的解决方案。不过有一个工作小提琴:http://jsfiddle.net/DUM7t/ 所以我不知道它为什么会坏。提前致谢!

编辑: 如果我将截图内容放在我的应用程序的运行块中,它也可以工作。

服务:

(function () {
  'use strict';

  angular
    .module('app')
    .service('PrintUtilService', PrintUtilService);

  PrintUtilService.$inject = ['$rootScope', '$timeout', '$interpolate', '$templateRequest', '$uibModal', 'APP', 'FORMATS'];
  /* @ngInject */
  function PrintUtilService($rootScope, $timeout, $compile, $templateRequest, $uibModal, APP, FORMATS) {
    var service = {
      printTemplate: printTemplate
    };

    return service;

    function printTemplate(){
      var data = ["1","2"];
      var html  =
        '<div>' +
        '<ul>' +
        '<li ng-repeat="score in data">{{score}}</li>' +
        '</ul>'+
        '</div>';

      var el = angular.element(html);

      $rootScope.data = data;
      var result = $compile(el)($rootScope); // error on this line

      $timeout(function() {
        console.log(el.html());
        alert(el.html());
      });
    }
  }
})();

【问题讨论】:

    标签: angularjs


    【解决方案1】:
    var scope = $rootScope.$new();
    scope.data = data;
    var result = $compile(el)(scope);
    

    【讨论】:

    • 尝试将 track by 添加到您的 ngrepeat:'
    • {{score}}
    • '
  • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
  • 通过 $index 添加曲目后,我仍然得到同样的错误
  • 猜你喜欢
    相关资源
    最近更新 更多
    热门标签