1

I'm trying to write a directive to provide table formatting. The idea is that the user passes the directive the list of objects (arr="ctrl.list") and the name of each object (elem="obj") and supplies the transcluded format for each table element...

<div ng-controller="Test as ctrl">
    <test-repeat arr="ctrl.list" elem="obj">
    the element: {{obj}}
    </test-repeat>    
</div>   

This is the directive...

angular
    .module('myApp')
    .directive('testRepeat', function() {
    return {
        template: 
            '<div ng-repeat="elem in arr"><span ng-transclude></span></div>',
        transclude: true,
        restrict: 'AE',
        scope: {
            arr: '=',
            elem: '='
        },
        link: function($scope, $elem, $attr) {
        }
    };    
});

And the controller:

angular
    .module('myApp')
    .controller('Test', function() {    
        var self = this;
        self.list = [ {title: 'one'}, {title: 'two'}, {title: 'three'} ];
});

While the array value (arr="ctrl.list") is properly bound to the directive scope and used by ng-repeat the elem value isn't, likely because these two variables are treated very differently by the ng-repeat directive.

Is it possible to re-write this directive to make the ng-repeat code use the value of elem specified by the user (i.e. obj)? And if I need to write my own version of ng-repeat using the transclude function (passed as a parameter to the link function) how would I watch each element of the array like ng-repeat does?

Here is a link to the jsfiddle.

Edit

As requested the desired output would be...

the element: {"title":"one"}
the element: {"title":"two"}
the element: {"title":"three"}

With the example of the html shown above (i.e. the element: {{obj}}). The broader idea being that the user could customise how they want obj to be displayed though.

CSharp
  • 1,396
  • 1
  • 18
  • 41
  • Please show us what your desired output would be. – Anid Monsur Sep 01 '15 at 16:41
  • Have edited the post accordingly... – CSharp Sep 01 '15 at 16:47
  • The `elem` in ng-repeat doesn't get bound to the scope, so you can't export it out of the directive like that. You can only use that variable within the ng-repeat container. – Anid Monsur Sep 01 '15 at 16:51
  • If, and it's a big if, I understand that post correctly it's quite different from my question. It looks like the name `$item` is hard-coded into the `template` variable in the link function. – CSharp Sep 01 '15 at 20:00

0 Answers0