Angular.js的getElementById()在$范围功能无法正常工作 [英] Angular.js getElementById() not working in $scope function

查看:368
本文介绍了Angular.js的getElementById()在$范围功能无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

EL =的document.getElementById(id)的;不工作时,下面的函数内... el的为空。在浏览器的调试,我可以拉起来用相同的code中的元素。我是新来Angular.js。我能不能连接到范围函数中使用常规的JavaScript?

  myappApp.controller('滚轮',函数($范围,$位置$ anchorScroll){
    $ scope.scrollTo =功能(ID){
    EL =的document.getElementById(id)的;
    }


解决方案

我觉得DOM没有加载呢。所以请确保的getElementById()运行DOM完全加载后。如果你的负荷事件触发后的失败,这是源于另一个原因。

HTML

 <机身NG控制器=样品>
    < H1 ID =foo的>巴≤; / H1>
< /身体GT;

JS

  VAR应用= angular.module('对myApp',[]);    app.controller('样品',函数($范围){        的addEventListener('负荷',负载,FALSE);        功能负荷(){
            VAR EL =的document.getElementById(富);
            警报(EL);
        }    });

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

解决方案

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

    });

这篇关于Angular.js的getElementById()在$范围功能无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆