将外部加载的 DOM 元素绑定到 Angular 的作用域 [英] Bind an externally loaded DOM element to Angular's scope

查看:21
本文介绍了将外部加载的 DOM 元素绑定到 Angular 的作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Angular 应用中使用 Google 地图.根据 Google Maps 的 API,我将 string 传递给包含 HTML 的 google.maps 函数,然后图书馆将其作为 InfoView 显示在地图上.

I'm using Google Maps within an Angular app. As per Google Maps's API, I pass a string to a google.maps function containing HTML, and the library displays it on the map as an InfoView.

我正在向此视图添加一个按钮,并且我希望此视图绑定到我的 Angular 应用程序中的控制器,但是,即使我通过 <div ng-controller="MyController">...</div>,当 Maps 库将其附加到 DOM 时,Angular 不会收到通知.

I'm adding a button to this view, and I want this view to be bound to a controller in my Angular app, however, even if I pass <div ng-controller="MyController">...</div>, when the Maps library attaches it to the DOM, Angular is not notified.

如何强制编译这个元素(我几乎没有控制权:只传递一个字符串)?

How can I force the compilation of this element (over which I have very little control: just passing a string)?

推荐答案

为了让 AngularJS注意到"指令,它需要编译元素,这不会自动完成,除非引导应用程序时.因此,要么 API 需要允许您将 DOM Element 传递给它(并且您需要在传递它之前 $compile 并链接它),或者您需要找到添加到DOM后的元素,然后$compile并链接它.AFAIK,如果您不能做到其中任何一个,那么您所要求的就是不可能的.

For AngularJS to "notice" the directive, it'd need to compile the element, which is not done automatically except when bootstrapping the application. So either the API needs to allow you to pass DOM Element to it (and you need to $compile and link it before you pass it on), or you need to find the element after it is added to DOM and then $compile and link it. AFAIK, if you cannot do either of those, then what you're asking is impossible.

如果您设法掌握元素,编译它是就像打电话一样简单

If you manage to get hold of the element, compiling it is as simple as calling

$compile(element)($scope);

其中 $scope 是您想要将其链接到的范围(甚至可能是 $rootScope).

where $scope is the scope you want to link it to (possibly even $rootScope).

这篇关于将外部加载的 DOM 元素绑定到 Angular 的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆