问题
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.
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)?
回答1:
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);
where $scope is the scope you want to link it to (possibly even $rootScope).
来源:https://stackoverflow.com/questions/27110875/bind-an-externally-loaded-dom-element-to-angulars-scope