10

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);
    }
  }
});

3 Answers 3

17

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/

Sign up to request clarification or add additional context in comments.

3 Comments

jqLite doesn't have insertAfter so if you're not using jQuery you have to use .after instead.
Question: why do you need to swap the elements? I'm unclear why it doesn't "just work" if you append the elements to be inserted to the current element.
The swap is needed because each row of the repeat renders in the original position (before any rows we've already appended). So the swap just checks if there's an appended row after and moves it before the current row.
3

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

1 Comment

Thanks, but it doesn’t work as I want to – it append all rows at end of table. See my update: jsfiddle.net/3gt9J/2
0

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>'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.