无法从Angular UI模式中的id获取元素

时间:2014-09-15 04:35:23

标签: angularjs angular-ui

我有一个AngularJS应用程序,带有Angular-UI Modal。我想从控制器中检索模态HTML中定义的DOM元素,但它返回undefined

我在Plunker(http://plnkr.co/edit/eoOuJiVaYASH1jMO8t2q?p=preview)上传了我的代码。

ModalInstanceCtrl控制器中,如果我尝试检索模态模板中定义的元素myElem,它会给我一个未定义的异常,如下所示,但如果我评论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)

我在下面的代码中遗漏了什么?

谢谢,

3 个答案:

答案 0 :(得分:5)

$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');
  });

答案 1 :(得分:3)

正如你所说的那样,DOM是在执行控制器之后构建的。尝试将$ timeout注入模态控制器并将$ timeout设置为0。

答案 2 :(得分:1)

实际上它应该是

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

而不是

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

删除$符号。它将打开模态窗口。