kuboslav
kuboslav

Reputation: 1460

AngularJS – append row after element in directive

My question is similar as this one, but instead of prepending row, I want it to append.

This doesn’t work:

app.directive('createTable', function ($compile) {
  return {
    link: function (scope, element, attrs) {
      var contentTr = angular.element('<tr><td>test</td></tr>');
      contentTr.parentNode.insertBefore(element, contentTr.nextSibling);
      $compile(contentTr)(scope);
    }
  }
});

Upvotes: 10

Views: 26122

Answers (3)

NDY
NDY

Reputation: 3557

Just wanted to add something because I had some minutes until it worked. If you don't have jQuery in your project you can't use the insertAfter. Just use after() from jQuery API .after()

I needed to add some elements in my directive between to other childs.

element.children().eq(0).after(angular.element('<p>Test</p>'));

Upvotes: 0

noj
noj

Reputation: 6759

This does the job:

app.directive('createTable', function ($compile) {
    return {
        link: function(scope, element, attrs) {
            if (element.next().length) {
                element.next().insertBefore(element);
            }

            var contentTr = angular.element('<tr><td>test</td></tr>');
            contentTr.insertAfter(element);
            $compile(contentTr)(scope);
        }
    }
});

http://jsfiddle.net/3gt9J/3/

Upvotes: 17

Arun P Johny
Arun P Johny

Reputation: 388316

I think you need

app.directive('createTable', function ($compile) {
    return {
        link: function (scope, element, attrs) {
            var contentTr = angular.element('<tr><td>test</td></tr>');
            contentTr.insertAfter(element);
            $compile(contentTr)(scope);
        }
    }
});

Demo: Fiddle

Upvotes: 3

Related Questions