简体   繁体   English

无法在Angular的控制器内获取元素

[英]Can't get element inside controller in Angular

I am trying to get an element inside an AngularJS controller like this: 我试图像这样在AngularJS控制器中获取一个元素:

var imageInput = document.getElementById("myImage");

It doesn't work, the element is null. 它不起作用,该元素为null。 However if I move the statement to a function that I bound with ng-click it works. 但是,如果将语句移到与ng-click绑定的函数上,它将起作用。 Why? 为什么? and how do I fix it? 以及如何解决?

Because it's not rendered for that time. 因为当时没有渲染。 If you write all code, we'll suggest better alternative than working with dom in controller (it's no good for you :) ) 如果您编写所有代码,我们将建议比在控制器中使用dom更好的替代方法(这对您不利:))

Like Karaxuna said, it has not been rendered yet. 就像Karaxuna所说的那样,它尚未被渲染。

Depending on what you are trying to do, you could use a directive to add behavior to your element : http://docs.angularjs.org/guide/directive . 根据您要尝试执行的操作,可以使用指令将行为添加到元素: http : //docs.angularjs.org/guide/directive

Add some code so we can give you a better answer. 添加一些代码,以便我们为您提供更好的答案。

Not only it may have not been rendered in your dom, but also you should inject the $window in your controller and then access the document like this: 不仅它可能尚未在您的dom中呈现,而且还应该将$window注入到控制器中,然后按以下方式访问文档:

    var myCtrl = function($scope,$window) {
       Var document = $window.document
       ...
    }

But you should seek a better way to manipulate your DOM instead of doing so in your controller (eg Writing a directive) 但是您应该寻求一种更好的方式来操作DOM,而不是在控制器中进行操作(例如,编写指令)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM