在AngularJS中的指令元素之后插入具有属性值或作用域模型的另一个元素

时间:2013-09-06 11:09:56

标签: angularjs angularjs-directive angularjs-scope

我想创建一个指令,在使用ng-repeat指令创建的每个<dd>元素之后创建一个<dt>元素。如何设置<dd>的内容等于指令属性值或ng-repeat范围模型值?

<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 个答案:

答案 0 :(得分:0)

在指令上设置scope以传递每个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/