简体   繁体   English

将ngRepeat包装在另一个指令中

[英]Wrapping an ngRepeat inside another directive

I'm trying to write a paginator as a directive for my application, but I can't seem to get it to work. 我正在尝试为我的应用程序编写一个分页器作为指令,但是我似乎无法使其正常工作。 Every where I've looked suggests using $compile , but I can't get that to work at all. 我看过的所有地方都建议使用$compile ,但我根本无法使用它。

This is what I have, and you can view a live demo 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);
      }
    }
  };
});

As you can probably tell, I'm quite new to angular, and any help will be greatly appreciated. 如您所知,我对angular还是很陌生,任何帮助将不胜感激。

I've managed to make it work by storing the data on the main directive's controller, rather than on the scope, which you can see here . 我设法通过将数据存储在main指令的控制器上而不是作用域上来使它起作用,您可以在此处看到。

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);
      }
    }
  };
});

You have two major problems here: 这里有两个主要问题:

First, Your directives doesn't share the same scope: 首先,您的指令不具有相同的范围:

在此处输入图片说明

Second, Inside you directive you refer to an outer scope variable items : 其次,在您的内部指令中,您引用外部作用域变量items

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM