最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular.js getElementById() not working in $scope function - Stack Overflow

programmeradmin0浏览0评论

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

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);
    }
Share Improve this question asked Apr 13, 2014 at 23:55 dmandman 11.1k25 gold badges116 silver badges217 bronze badges 1
  • 5 document.getElementById doenst work cause the dom is maybe not loaded when the script is executed. Thats why the function retuns nothing. Anyway: There is no use in doing that. When you wanna change the element you can use directives from angular or bind the element to an angular-model. Accessing the element in the controller is bad practice and rarely/never needed. Just tell us what you wanna do and we may help you – Fuzzyma Commented Apr 13, 2014 at 23:58
Add a comment  | 

1 Answer 1

Reset to default 12

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

    });
发布评论

评论列表(0)

  1. 暂无评论