【问题标题】:TypeError: Cannot read property 'childNodes' of undefined in AngularJS directiveTypeError:无法读取 AngularJS 指令中未定义的属性“childNodes”
【发布时间】:2013-07-26 17:15:15
【问题描述】:

我正在像这样在 AngularJS 中创建一个指令“Tab Slide Out”

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 个或更多,它会抛出这个错误 TypeError: Cannot read property 'childNodes' of undefined

这是plunker链接 Demo

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-02-18
      • 2014-12-29
      • 2015-12-08
      • 2015-08-26
      • 2016-09-12
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      • 2019-04-22
      相关资源
      最近更新 更多