AngularJS – append row after element in directive

跟風遠走 提交于 2019-12-30 08:17:12

问题


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

回答1:


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/




回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/18483324/angularjs-append-row-after-element-in-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!