Search code examples
javascriptangularjsangularjs-directiveangularjs-ng-repeattransclusion

AngularJS : ng-repeat in Directive ng-transclude


Hi I am new to AngularJS so forgive me if this is a simple problem. I have a simple directive that looks something like this:

app.directive('myDirective', function() {
    return {
        restrict: 'E',
        transclude: true,
        replace: true,
        template: '<div ng-transclude></div>'
    };
});

I would ideally like the content that gets inserted into my div with ng-transclude to be generated using ng-repeat. So I have an HTML block like this:

<my-directive>
    <div ng-repeat="item in data">{{item.name}}</div>
</my-directive>

I know that my data array is populated in my controller properly as I can see the requests in my dev tool and i have logged my data object. However, my page isn't generated correctly, all I end up with is something like the following when I inspect my page content:

<my-directive>
    <!-- ngRepeat: item in data -->
</my-directive>

Is there something wrong with using ng-repeat inside of ng-transclude? I have searched but can't seem to find the answer. Thanks!

EDIT:

Here is the controller:

app.controller('MyController', ['$scope', function($scope) {
    $scope.data = [{'name': 'Foobar'}];
}]);

Solution

  • There's probably some issue of scope visibility between your controller and your directive.

    Take a look at [this jsFiddle].

    var myModule = angular.module('ui.directives', []);
    myModule.directive('myDirective', function() {
        return {
            restrict: 'E',
            transclude: true,
            replace: true,
            template: '<div ng-transclude></div>'
        };
    });
    
    myModule.controller('myController', function($scope){
        $scope.data = [
            {name: 'foo'},
            {name: 'bar'}
        ];
    });
    
    angular.module('myApp', ['ui.directives']);