Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 276
Shaun Xu Avatar asked Sep 13 '26 00:09

Shaun Xu


2 Answers

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

like image 127
Randika Avatar answered Sep 16 '26 07:09

Randika


$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');
  });
like image 31
xinyu Avatar answered Sep 16 '26 08:09

xinyu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!