【问题标题】:Wrapping an ngRepeat inside another directive将 ngRepeat 包装在另一个指令中
【发布时间】:2014-01-27 05:23:58
【问题描述】:

我正在尝试编写一个分页器作为我的应用程序的指令,但我似乎无法让它工作。我看过的每个地方都建议使用$compile,但我根本无法让它工作。

这是我的,你可以观看现场演示here

var app = angular.module('myApp', []);

app.controller('MyController', function($scope) {
  $scope.items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
});

app.directive('myPaginator', function() {
  return {
    restrict : 'A',
    priority : 1000,

    scope : {
      items : '=myPaginator'
    },

    controller : function($scope) {
      $scope.amount = 5;
    }
  };
});

app.directive('myPaginatorItem', function($compile) {
  return {
    restrict : 'A',
    require  : '^myPaginator',
    priority : 999,

    compile : function(element) {
      element
        .removeAttr('my-paginator-item')
        .attr('ng-repeat', 'item in items | limitTo:amount');

      return function($scope, element) {
        $compile(element)($scope);
      }
    }
  };
});

您可能会说,我对 Angular 还是很陌生,任何帮助都将不胜感激。

【问题讨论】:

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


    【解决方案1】:

    我已经设法通过将数据存储在主指令的控制器上来使其工作,而不是存储在范围内,您可以看到 here。

    var app = angular.module('myApp', []);
    
    app.controller('MyController', function($scope) {
      $scope.items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    });
    
    app.directive('myPaginator', function() {
      return {
        restrict : 'A',
        priority : 1000,
        replace  : true,
    
        scope : {
          items : '=myPaginator'
        },
    
        controller : function($scope) {
          this.items = $scope.items;
          this.amount = 5;
        }
      };
    });
    
    app.directive('myPaginatorItem', function($compile) {
      return {
        restrict : 'A',
        require  : '^myPaginator',
        priority : 999,
        scope    : {},
    
        compile : function(element) {
    
    
          element
            .removeAttr('my-paginator-item')
            .attr('ng-repeat', 'item in paginator.items | limitTo:paginator.amount');
    
          return function($scope, element, $attrs, paginator) {
            $scope.paginator = paginator;
            $compile(element)($scope);
          }
        }
      };
    });
    

    【讨论】:

      【解决方案2】:

      这里有两个主要问题:

      首先,您的指令不共享相同的范围:

      其次,在指令内部,您引用了外部范围变量items:

      .attr('ng-repeat', 'item in items | limitTo:amount');
      

      【讨论】:

      • 是的,它们不共享相同的范围,但是为什么第二个范围有项目但没有数量,而第一个范围两者都有。有没有办法让第二个范围成为第一个范围的孩子?另外,你会怎么做我想做的事?
      • 它只是从父范围获取项目,因为它不是孤立的。请提供您想要实现的目标的更多详细信息
      • 另外,为什么引用外部范围变量是个问题?项目可用,金额不是因为第二个范围由于某种原因不是孩子,即使它应该是?
      • 我想让第二个作用域成为第一个作用域的子作用域,所以第一个作用域上可用的所有属性在第二个作用域上也可用
      • 或者让他们共享一个作用域
      猜你喜欢
      • 2018-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-08
      • 1970-01-01
      • 2016-09-26
      • 1970-01-01
      相关资源
      最近更新 更多