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
1 Answer
Reset to default 12I 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);
}
});