将在AngularJS中迭代的列表附加到HTML DOM

时间:2017-09-30 17:47:16

标签: javascript html angularjs dom angularjs-ng-repeat

所以我有一个AngularJS函数,在调用时应该将一个列表元素添加到DOM中的div,并且列表应该是ng-repeat,以便它可以迭代列表中的对象。

列表中的这些对象包含一些我想要打印出来的属性。

AngularJS计划的一部分

var el = angular.element(document.getElementById('categories'));
el.append('<ul id="' + categoryItemStr + '"><li ng-repeat="item in categories[currentCategory]"><h4 class="h4">{{item.itemName}}</h4>{{item.itemDescription}}<br><span style="font-size:11px;">{{item.itemPrice}}.00 $</span></li></ul>');

但是当我运行它时,它不是可重复的,看起来javascript还没有呈现。重要的是要注意,当页面加载时我在文档中已经有相同的HTML,并且当它没有出现在角度函数中但是写在HTML文档中时它工作正常。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

  

但是当我运行它时,它不是可重复的,看起来javascript没有呈现。

如果您想让AngularJs通过指令ng-repeat了解您的DOM,首先需要compile使用$compile

让我们说这是你的根:

<div id="categories" some-dir></div>

其中some-dir指令是:

app.directive('someDir', function($compile) {
  return {
    restrict: 'A',
    link: function(scope, elm, attrs) {
      scope.categories = [{
        itemName: "itemName",
        itemPrice: 11
      }];
      var categoryItemStr = 'someId';
      var el = angular.element(document.getElementById('categories'));
      el.append('<ul id="' + categoryItemStr + '"><li ng-repeat="item in categories[currentCategory]"><h4 class="h4">{{item.itemName}}</h4>{{item.itemDescription}}<br><span style="font-size:11px;">{{item.itemPrice}}.00 $</span></li></ul>');
      var e = angular.element(el);
      $compile(e.contents())(scope);
      elm.replaceWith(e);
      }
  };
});

一些简单的Demo in Fiddle