Shaun Xu
Shaun Xu

Reputation: 4666

Cannot get element from id inside an Angular UI Modal

I have an AngularJS application with Angular-UI Modal. I'd like to retrieve a DOM element defined inside the modal HTML from the controller, but it returned undefined.

I uploaded my code in Plunker (http://plnkr.co/edit/eoOuJiVaYASH1jMO8t2q?p=preview).

In the ModalInstanceCtrl controller if I tried to retrieve the element myElem defined in the modal template it gave me an undefined exception as below but works well if I commented var elem = $document.getElementById('myElem');.

TypeError: undefined is not a function
    at new  (http://run.plnkr.co/K8SndGsk5DANhGl2/:36:28)
    at invoke (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:3918:17)
    at Object.instantiate (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:3929:23)
    at http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:7216:28
    at resolveSuccess (http://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.10.0/ui-bootstrap-tpls.js:1710:32)
    at wrappedCallback (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:11498:81)
    at http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:11584:26
    at Scope.$eval (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:12608:28)
    at Scope.$digest (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:12420:31)
    at Scope.$apply (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:12712:24)

Did anything I miss in the code below?

Thanks,

Upvotes: 2

Views: 9203

Answers (3)

xinyu
xinyu

Reputation: 61

$scope.openModal = function () {
  var modal = $modal.open({
    animation: false,
    templateUrl: 'app/modules/demo/modal.html',
    controller: 'MyModalCtrl',
    resolve: {
      vm: function () {
        return 'id';
      }
    }
  });
  modal.rendered.then(function () {
     //process your logic for DOM element
     console.info(document.getElementById('elementIdInModalTemplate');
  });

Upvotes: 6

Randika
Randika

Reputation: 753

As you said the DOM was constructed after the controller was executed.Try injecting $timeout into the modal controller and set $timeout to 0.

Upvotes: 6

RahulB
RahulB

Reputation: 2110

Actually it should be

var elem = document.getElementById('myElem');

instead of

var elem = $document.getElementById('myElem');

Remove the $ sign. It will open up the modal window.

Upvotes: 1

Related Questions