Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js getElementById() not working in $scope function

el = document.getElementById(id); is not working when inside the below function...the el is null. In the browser debug I can pull up the element with the same code. I am new to Angular.js. Can I not use regular javascript in a function attached to the scope?

myappApp.controller('Scroller', function($scope, $location, $anchorScroll) {
    $scope.scrollTo = function(id) {
    el = document.getElementById(id);
    }
like image 585
dman Avatar asked Apr 13 '14 23:04

dman


1 Answers

I think DOM is not loaded yet. So please make sure getElementById() run after DOM is loaded completely. If you fail after the 'load' event fires, this is resulted from another cause.

HTML

<body ng-controller="sample">
    <h1 id="foo">bar</h1>
</body>

JS

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

    app.controller('sample', function($scope){

        addEventListener('load', load, false);

        function load(){
            var el = document.getElementById("foo");
            alert(el);
        }

    });
like image 195
Tamura Avatar answered Nov 09 '22 07:11

Tamura