简体   繁体   中英

Can't get element inside controller in Angular

I am trying to get an element inside an AngularJS controller like this:

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

It doesn't work, the element is null. However if I move the statement to a function that I bound with ng-click it works. 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 :) )

Like Karaxuna said, it has not been rendered yet.

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 .

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:

    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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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