[英]Why am I getting null for document.getElementById here?
Codepen: http://codepen.io/leongaban/pen/YyWmOo?editors=101 Codepen: http ://codepen.io/leongaban/pen/YyWmOo?editors = 101
In my app , I have a simple array of div id names media = ["twitter", "news", "blogs"]
在我的应用中 ,我有一个简单的div ID名称数组
media = ["twitter", "news", "blogs"]
I then have a simple for loop which attempts to grab the #ids from the markup and add them into my vm.parameters
object. 然后,我有一个简单的for循环,它尝试从标记中获取#id并将其添加到我的
vm.parameters
对象中。
Currently the div's are showing as null
: 当前div显示为
null
:
Code in my Controller: 我的控制器中的代码:
var vm = this;
vm.parameters = {};
var media = ['twitter', 'news', 'blogs'];
console.log(vm);
console.log(media);
initParameters();
function initParameters() {
console.log('initParameters called...');
for (var i=0; i<media.length; i++) {
vm.parameters[media[i]] = {};
vm.parameters[media[i]].start = 0;
vm.parameters[media[i]].limit = 10;
vm.parameters[media[i]].total = 0;
vm.parameters[media[i]].div = document.getElementById(media[i]);
console.log('getElementById =',document.getElementById(media[i]));
}
console.log('media = ',media);
console.log('vm.parameters = ',vm.parameters);
}
Markup (Using the Ionic framework ): 标记(使用Ionic框架 ):
<ion-slide id="twitter">
<h3>Twitter stream</h3>
<p>Here is content for Twitter</p>
</ion-slide>
<ion-slide id="news">
<h3>News stream</h3>
<p>Here is content for News</p>
</ion-slide>
<ion-slide id="blogs">
<h3>Blogs</h3>
<p>Here is content for blogs</p>
</ion-slide>
You will need to do an onload
event before trying to get the id's. 在尝试获取ID之前,您需要执行
onload
事件。 This is because the controllers run before the DOM loads: 这是因为控制器在DOM加载之前运行:
window.onload = function(){
initParameters();
}
DOM code doesn't belong in controllers. DOM代码不属于控制器。 The controller will run before the route template is even loaded so you are looking for elements that don't exist yet.
该控制器将在甚至加载路径模板之前运行,因此您正在寻找尚不存在的元素。
Generally there shouldn't be any need to look for elementById
. 通常,不需要寻找
elementById
。 Normally you would let your data model drive creation of the view 通常,您将让数据模型驱动视图的创建
If you must do dom manipulation like this you need to do it in a directive to be assured the element(s) exist when your code runs 如果必须像这样进行dom操作,则需要在指令中进行操作,以确保在代码运行时元素存在
You can also use 您也可以使用
$rootScope.$on('$viewContentLoaded', function(){
// your code
});
in your angular.run()
, will execute once content loaded. 在您的
angular.run()
,将在加载内容后执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.