javascript - AngularJS 如何使用 ng-repeat $compile 元素?

标签 javascript angularjs angularjs-directive angularjs-scope angularjs-ng-repeat

我似乎无法弄清楚这一点。我需要使用 $compile(我认为)来将元素与范围连接起来。这适用于没有其他指令(特别是 ng-repeat)的元素。但不适用于具有 ng-repeat 的元素。我想出了一个例子:

Plunkr:http://plnkr.co/edit/Nmn7n631iijP1lQAZaXv?p=preview

var count = 0;
angular.module("dir", [])

.controller("main", function($scope) {
  $scope.test = 1;
})

.directive('ngHello', function($compile) {
  return {
    scope: true,
    compile: function(telem, attrs, transclude) {
      var repeat = "<div>"+
      "<div ng-repeat='item in items'>{{item}}</div>"+
      "</div>";
      var r = angular.element(repeat);
      telem.after(r);

      var easy = "<div>this is {{test2}}</div>";
      var e = angular.element(easy);
      telem.after(e);


      return {
        pre: function(scope, ielem, iAttrs, controller) {
          $compile(r)(scope); //why doesn't this seem to work?
          $compile(e)(scope);
        },
        post: function(scope, ielem, iAttrs, controller) {
          scope.items = [];
          for(var i=0; i<5; i++) {
            scope.items.push(count++);
          }
          scope.test2 = "test4";
        }
      };
    }
  };
});

我做错了什么?

最佳答案

你不需要调用 angular.element,$compile 会获取 html。你甚至不需要使用指令的编译函数,这都可以在链接函数中完成。 $compile 返回编译后的元素。您需要将其用作要添加的元素。

来自 plunkr 的相关位:

.directive('ngHello', function($compile) {
  var repeat = "<div>"+
  "<div ng-repeat='item in items'>{{item}}</div>"+
  "</div>";
  var r = angular.element(repeat);
  return {
    scope: true,
    link: function(scope, elem, attrs) {
      scope.items = [];
      scope.items.push(1);
      scope.items.push(2);
      scope.items.push(3);
      var e = $compile(repeat)(scope);
      elem.after(e);

关于javascript - AngularJS 如何使用 ng-repeat $compile 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23532261/

相关文章:

angularjs - $emit 事件不适用于 ng-if

javascript - 将一些属性传递给 AngularJS 中的指令

javascript - 使用映射和字符串模板文字转换对象键值

javascript - 表格单元格元素中的 Angular 嵌入

javascript - 从未调用过自定义 Angular 过滤器?

javascript - Angular 面包屑 "10 $digest() iterations reached. Aborting! "

angularjs - 在AngularJS中循环不起作用

javascript - 删除任何记录时出现 Sails.js 错误问题

javascript - Angular ng-switch 方法在页面渲染后隐藏 html 元素

javascript - 自定义元素中的 Aurelia 双向绑定(bind)不起作用