类型错误:无法读取 AngularJS 指令中未定义的属性“childNodes" [英] TypeError: Cannot read property 'childNodes' of undefined in AngularJS directive

查看:26
本文介绍了类型错误:无法读取 AngularJS 指令中未定义的属性“childNodes"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制定指令Tab Slide Out";在像这样的 AngularJS 中

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

如果我只使用一个,一切正常.但是,如果我使用 2 个或更多,它会抛出这个错误类型错误:无法读取未定义的属性childNodes"

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

这是plunker链接演示

Here is the plunker link Demo

推荐答案

发生的情况是,当您添加另一个滑块时,它使用与第一个相同的 handlercontainer 引用一.由于 append 实际上会移动元素(如果元素当前存在于 DOM 中),它会从第一个指令中删除.

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.

您需要为每个实例创建新元素(或克隆它们).http://plnkr.co/edit/CC2bCXdaoAo7HjQ0oAu0?p=preview

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

这篇关于类型错误:无法读取 AngularJS 指令中未定义的属性“childNodes"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆