0
votes

I want to create a directive that creates a <dd> element after each <dt> element created with ng-repeat directive. How do I set the content of the <dd> equal to directive attribute value, or ng-repeat scope model value?

<dl>
  <dt ng-repeat="item in items" insert-dd="{{ item.dd_vaue }}">{{ item.dt_value }}</dt>
</dl>

angular.directive('insertDd', function () {
  restrict: 'A',
  link: function (scope, element, attrs) {
    var dd = angular.element('<dd> here is attrs.insertDd or scope.item.dd_value </dd>');
    dd.insertAfter(element);
    $compile(dd)(scope);
  }
});
1

1 Answers

0
votes

Set up a scope on the directive to pass each item:

app.directive('insertDd', function ($compile) {
    return {
        restrict: 'A',
        scope: {
            item: '=insertDd'
        },
        link: function (scope, element, attrs) {
            // ng-repeat always inserts the next item directly after the last one,
            // so this element will actually be before the <dt> we just added
            if (element.next().length) {
                element.next().after(element);
            }

            var dd = angular.element('<dd> here is {{item.dd_value}} or {{item.dt_value}} </dd>');

            element.after(dd);
            $compile(dd)(scope);
        }
    };
});

http://jsfiddle.net/sFEf5/2/