Search code examples
javascriptangularjsangularjs-scopelistjs

"Cannot read property 'childNodes' of undefined" adding controller to list element with list.js


I am trying to create a list object using the list.js library and to add it to the angular.js root scope in order to use it in the nested scopes. This works fine as long as I don't add a controller to the list elements.

If I do so a I get the following error in the javascript console.

"Cannot read property 'childNodes' of undefined"

Same happens if the list is initialised inside an init() function called with ng-init.

Here are the html and js files

<html>
<head>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/list.js/1.1.1/list.min.js"></script>
    <script type="text/javascript" src="listBug.js"></script>
</head>
<body ng-controller="MainController" ng-app="theApp">
<div id="theList">
    <ul class="list">
        <li>
            <div ng-controller="divController">
                <span class="id"></span>
            </div>
        </li>
    </ul>
</div>      
</body>

</html>

listBug.js

var app = angular.module('theApp', [])

mainController=function($scope){

    var opts={valueNames: ['id'] }
    $scope.theList=new List('theList', opts);
}

app.controller("MainController", mainController)


divController=function($scope){

}

app.controller("divController", divController)

Solution

  • The problem is that the DOM isn't fully loaded when your code is being called. You can delay it by doing the following

    mainController=function($scope){
        angular.element(document).ready(function () {
            var opts={valueNames: ['id'] } 
            $scope.theList=new List('theList', opts);
        });
    }