不能在指令的模板中使用ng-repeat。

问题描述 投票:1回答:1

我无法让我的ng-repeat在指令模板中工作。它显示为 "ngRepeat: day in days track by $index"。

    angular .module('Auto') .directive('calendar', CalendarDirective);
CalendarDirective.$inject = ['$interpolate'];
CalendarDirectiveController.$inject = ['$scope', '$rootScope', '$attrs', '$location'];

function CalendarDirective($interpolate) {
    return {
        restrict: 'E',
        scope: true,
        template: $('#template-calendar').html(),
        replace: true,
        link: function(scope, element) {
            var startSym = $interpolate.startSymbol();
            var endSym = $interpolate.endSymbol();
            var rawExp = element.html();
            var transformedExp = rawExp.replace(/<@/g, startSym).replace(/@>/g, endSym);
            var parsedExp = $interpolate(transformedExp);
            scope.$watch(parsedExp, function(newValue) {
                element.html(newValue);
            });
        },
        controller: CalendarDirectiveController,
    };
}

function CalendarDirectiveController($scope, $rootScope, $attrs, $location) {
    $scope.monthText = moment().format('MM YYYY');
    $scope.days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

    $scope.title = function () {
        return 'Directive';
    }
}

<script type="text/html" id="template-calendar"> <div> <table> <thead> <tr ng-repeat="day in days track by $index"> <th><@day@></th> </tr> </thead> <tbody> <tr> </tr> </tbody> </table> </div>

I'm currently out of ideas

Here is the plunker

angularjs angularjs-directive
1个回答
1
投票

$interpolateProvider 已经完成了工作,即

angular.module('plunker', [], function($interpolateProvider) {
        $interpolateProvider.startSymbol('<@');
        $interpolateProvider.endSymbol('@>');
})

所以你不需要一个 $watch 里面 link.

function CalendarDirective($interpolate) {
    return {
        restrict: 'E',
        scope: true,
        template: $('#template-calendar').html(),
        replace: true,
        link: function(scope, element) {
           // removed 
        },
        controller: CalendarDirectiveController,
    };
}

灌篮机演示

© www.soinside.com 2019 - 2024. All rights reserved.