Onsen UI v2, stopped working document.getElementById("id")



  • After upgrade Onsen UI v1 to v2, stopped working: document.getElementById(“id”)

    Small example in Codepen: http://codepen.io/anon/pen/xZYGOZ

    index.html:

    <body ng-app="app">
    <ons-tabbar var="tabbar" ng-controller="MainCtrl">
        <ons-tabbar-item
            icon="home"
            label="Home"
            page=home.html"
            active="true"></ons-tabbar-item>
        <ons-tabbar-item
            icon="ion-compass"
            label="Map"
            page="map.html" ></ons-tabbar-item>
    </ons-tabbar>
    </body>
    

    map.html:

    <div ng-controller="MapCtrl">
        <div id="map-canvas"></div>
    </div>
    

    controllers.js:

    app.controller('MapCtrl',['$scope',
    function($scope){        
        var mapContainer = document.getElementById('map-canvas');
        console.log(mapContainer);// null
        mapContainer.style.width = '200px';// TypeError: mapContainer is null
        mapContainer.style.height = '200px';
        var mapOptions = {
            center: new google.maps.LatLng(50.5, 30.5),
            zoom: 8,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        $scope.map = new google.maps.Map(mapContainer, mapOptions);
    }
    ]);

  • Onsen UI

    Probably #map-canvas is not attached to the DOM by the time you try to find it. Try to find when it is attached and wait for it.



  • @Fran-Diox said:

    Probably #map-canvas is not attached to the DOM by the time you try to find it. Try to find when it is attached and wait for it.

    I undestand. but how - “Try to find when it is attached and wait for it”?


  • Onsen UI

    @operun A good way would be to make a small example in Codepen where this happens. Otherwise if you want some help, please describe how your app is structured and add more code to the question.



  • @Fran-Diox said:

    @operun A good way would be to make a small example in Codepen where this happens. Otherwise if you want some help, please describe how your app is structured and add more code to the question.

    Small example in Codepen: http://codepen.io/anon/pen/xZYGOZ
    P.S. I do not know how to make in Codepen a dedicate HTML file (“home.html” and “map.html”),
    and so I used templates ( <ons-template id=“home.html”> ).
    My project in Monaca “home.html” and “map.html” - is dedicated files.


  • Onsen UI

    @operun I tested it a bit and looks like the controller runs before the DOM is ready. It works if you add 10ms timeout or so: http://codepen.io/frankdiox/pen/wMyBNp
    This could be a bug but in any case, the best place to initialize data in Onsen UI 2.0 is in the page’s init event.

    I will open an issue about this on Github and see if it’s fixable.



  • Thank you Fran Diox, init event - helped me.
    Сorrected small example in Codepen (with init event): http://codepen.io/anon/pen/xZYGOZ

    Also it works with use $templateCache


Log in to reply