无法替换ng-template中的元素

时间:2015-04-25 19:17:48

标签: javascript angularjs angularjs-directive

我正在尝试使用AngularJS创建一个可以具有递归树结构的指令,其中每个节点都可以在transclude部分中拥有自己的模板。

这是JS:

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
  $scope.input = [{
    name: 'blueberry cheesecake',
    color: 'blue',
    children: [{
      name: 'blueberry cheesecake',
      color: 'blue'
    }, {
      name: 'rocky road',
      color: 'mostly brown'
    }]
  }, {
    name: 'rocky road',
    color: 'mostly brown'
  }];
});
app.directive("auratree", function() {
  return {
    scope: {
      input: "="
    },
    template: function(element) {
      element.data("customListTemplate", element.find("item-template"));
      var c =
        '<script type="text/ng-template" id="auratree2">' +
        '<item-placeholder></item-placeholder>' +
        '        <div ng-if="item.children">' +
        '          <div ng-repeat="item in item.children" ng-include="' +
        "'" + 'auratree2' + "'" + '">' +
        '            <item-placeholder></item-placeholder></div>' +
        '        </div>' +
        '</script>' +
        '<div ng-repeat="item in input" ng-include = "' + "'" + 'auratree2' + "'" + '">' +
        '</div>';
      console.log(c);
      return c;
    },
    compile: function(tElement, tAttrs) {
      var template = tElement.data("customListTemplate");
      tElement.find("script").html(tElement.find("script").html().replace("<item-    placeholder></item-placeholder>", template.html()));
    }
  };

  function link(scope, element, attrs) {}
});

这是HTML

<!DOCTYPE html>
<html ng-app="plunker">
  <head>
    <meta charset="utf-8" />
    <title>Aura Tree</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.13/angular.js" data-semver="1.3.13"></script>
    <script src="auratree.js"></script>
  </head>
<body ng-controller="MainCtrl">
    <pre>template 1:</pre>
    <auratree input="input"> <item-template>
    {{$index}} | {{item.name}}
    <hr>
    </item-template> </auratree>
</body>
</html>

此代码

tElement.find("script")
   .html(tElement.find("script").html()
   .replace("<item-placeholder></item-placeholder>",template.html()));  

正在Chrome中使用,但在IE11中无效。

通常的element.replaceWith不起作用,所以我试图更改html ......但是没有成功。

请告诉我解决这个问题的方法。

这里是plunker

3 个答案:

答案 0 :(得分:1)

我不认为您使用ng-template的方法可以按预期工作。即使您设法替换ng-template中的占位符,如果您在应用中有多个<auratree>元素,每个元素都有不同的项目模板,那么所有元素都具有相同的(最后编译的)模板。 / p>

使用ng-include是一个聪明的伎俩,但这个问题有点复杂。不要依赖ng-include d模板,而是在link - 每个级别包含相同的指令 - 时间(ng-include无论如何都会这样做),并使用{{1} } transclude

由于根元素(只有一个项目数组)和每个子树(具有值item-template)之间存在一些不对称性,我添加了另一个指令来表示每个树项:

root指令仅重复每个项目并转换children

item-template

app.directive("tree", function(){ return { restrict: "E", scope: { items: "=" }, transclude: true, template: '<div ng-repeat="item in items">\ <tree-item item="item"></tree-item>\ </div>', link: function(scope){ scope.$level = -1; } }; }); 指令从父级转换treeItem,并重复子项,如果有的话:

item-template

用法是:

app.directive("treeItem", function($compile){
  return {
    scope: {
      item: "="
    },
    link: function(scope, element, attrs, ctrls, transclude){
      scope.$index = scope.$parent.$index;
      scope.$level = scope.$parent.$level + 1;

      transclude(scope, function(clone){
        element.append(clone.contents());
        var repeater = angular.element('<div ng-repeat="child in item.children">');
        var subtree = angular.element('<tree-item item="child">');

        element.append(repeater.append(subtree));

        $compile(repeater)(scope, null, { parentBoundTranscludeFn: transclude });
      });
    }
  };
});

<强> Demo

答案 1 :(得分:0)

最好将该模板放在角度# -*- coding: utf-8 -*- import scrapy from scrapy.selector import Selector class MySpider(scrapy.Spider): symbols = ["SCMP"] name = "yahoo" allowed_domains = ["yahoo.com"] def stock_list(symbols): start_urls = [] for symb in symbols: start_urls.append("http://finance.yahoo.com/q/is?s={}&annual".format(symb)) return start_urls start_urls = stock_list(symbols) def parse(self, response): revenue = Selector(response=response).xpath('//td[@align="right"]').extract() print(revenue) 的角度{&1;}的运行阶段内。从指令

中删除该模板

运行阻止

$templateCache

指令(模板功能)

 app.run(function($templateCache) {

     $templateCache.put('auratree2', '<item-placeholder></item-placeholder>' +
         '        <div ng-if="item.children">' +
         '          <div ng-repeat="item in item.children" ng-include="' +
         "'" + 'auratree2' + "'" + '">' +
         '            <item-placeholder></item-placeholder></div>' +
         '        </div>'
     );
 });

答案 2 :(得分:-1)

你的plunkr有JQuery,但你的StackOverflow问题没有,所以我假设你正在使用JQuery(你可能不得不因为JQLite的限制)。

在HTML文件中,修改JQuery和Angular的顺序,以便首先列出前者。

  <head>
    <meta charset="utf-8" />
    <title>Aura Tree</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <script data-require="jquery@*" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <script src="script.js"></script>
  </head>