TypeError: Cannot read property 'childNodes' of undefined in AngularJS directive

喜你入骨 提交于 2019-12-19 09:27:16

问题


I am making a directive "Tab Slide Out" in AngularJS like this

angular.module('myApp',[]).directive('tabSlideOut', ["$window", "$document", "$timeout", function($window, $document, $timeout) {
    // default settings of a regular tab slide out
    var defaultSettings = {
        speed: 300,
        action: 'click',
        tabLocation: 'left',
        top: '200px',
        left: '50px',
        fixedPosition: true,
        positioning: 'absolute',
        onLoadSlideOut: false
    }

    // handler element
    var handler = angular.element('<a class="handler btn">{{title}}</a>');

    // panel element aka container
    var container = angular.element('<div ng-transclude></div>');

    return {
        restrict: 'E',
        transclude: true,
        replace: true,
        template: '<div class="tab-slide-out"></div>',
        scope: {
            options: "=",
            status: "=",
            title: "@"
        },
        compile: function(template) {

            // append handler to template
            template.append(handler);

            // append container to template
            template.append(container);

            console.log(template);
            // return linking function
            return function(scope, element, attrs) {
               ...
            }
        }

    };

If I use only one, everything works fine. However, if I use 2 or more, it will throw this error TypeError: Cannot read property 'childNodes' of undefined

Here is the plunker link Demo


回答1:


What's happening is when you add another slider it uses the same handler and container references as the first one. As append will actually move the element if it currently exists in the DOM, it is removed from the first directive.

You need to create new elements for each instance (or clone them). http://plnkr.co/edit/CC2bCXdaoAo7HjQ0oAu0?p=preview



来源:https://stackoverflow.com/questions/17876213/typeerror-cannot-read-property-childnodes-of-undefined-in-angularjs-directive

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