我有一个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)
我在下面的代码中遗漏了什么?
谢谢,
答案 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');
删除$符号。它将打开模态窗口。