在ng-repeate中显示自定义指令每10个元素

时间:2016-02-18 13:56:31

标签: javascript angularjs angularjs-directive ng-repeat

我想在ngRepeat中的每个第十个元素之后显示横幅,并根据过滤器进行更改(目前我没有实现更改功能,但我会监听更改事件)。我已经为banner创建了以下指令:

(function () {
    'use strict';

    angular
        .module('calendar')
        .directive('banner', banner);

    banner.$inject = ['$rootScope', '$compile', 'bannerService'];

    // Usage: <div data-banner=""></div>
    function banner($rootScope, $compile, bannerService) {
        var config = {},
            templates = [],
            bannerRowTemplate = '<div class="row"><div class="carousel slide" data-ride="carousel"><div class="carousel-inner" role="listbox">{0}</div></div></div>',
            bannerItemTemplate = '<div class="item {0}">{1}</div>';

        var directive = {
            scope: {
                item: '=banner'
            },
            link: link,
            priority: 100001,
            restrict: 'A'
        };

        return directive;

        function link(scope, element, attrs) {
            if (scope.item) {
                bannerService.getBannersConfig(receivedConfig);

                $rootScope.$on('FiltersChanged', function (event, originEvents, sortType) {
                    element.html(getBannersHtml()).show();
                    $compile(element.contents())(scope);
                });
            }
        }

        function receivedConfig(data) {
            config = data.config;
            templates = data.banners;
        }

        function getBannersHtml() {
            var inner = '';

            for (var i = 0; i < templates.length; i++) {
                inner += bannerItemTemplate.format(i == 0 ? 'active' : '', templates[i]);
            }

            return bannerRowTemplate.format(inner);
        }
    }
  })();

我认为这是:

<div data-ng-repeat="event in events | offset: (currentPage - 1) * itemsPerPage | limitTo: itemsPerPage" data-repeat-finish="">
        <div eventtitle="event.title"></div>
        <div>{{event.date}}</div>

        <div data-banner="$index % 10 == 0"></div>
</div>

但指令不呈现。脚本执行,但指令内部html不会更改。我也尝试过ng-if,ng-show而不是将$ index%10传递给指令。

1 个答案:

答案 0 :(得分:0)

您可以使用ng-show或ng-if。 这两者之间的区别在于:

ng-if 如果为false则不呈现横幅。

ng-show 如果为false,则会展示横幅并将其隐藏。

从指令声明中删除项目绑定

var directive = {
    link: link,
    priority: 100001,
    restrict: 'A'
};

return directive;

function link(scope, element, attrs) {
    bannerService.getBannersConfig(receivedConfig);

    $rootScope.$on('FiltersChanged', function (event, originEvents, sortType) {
        element.html(getBannersHtml()).show();
        $compile(element.contents())(scope);
    });
}

然后像这样调用你的指令

<div data-ng-show="$index % 10 == 0" data-banner></div>

或者像这样

<div data-ng-if="$index % 10 == 0" data-banner></div>