javascript 动态创建角度视图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12046129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:09:49  来源:igfitidea点击:

Dynamically creating an angular view

javascriptjqueryhtmlangularjs

提问by Martin

I'm making an in game UI using awesomium, at some points the game loads up and executes a chunk of javascript which is meant to create arbitrary new UI elements. e.g.

我正在使用 awesomium 制作游戏内 UI,在某些时候,游戏会加载并执行一段 javascript,它旨在创建任意的新 UI 元素。例如

jQuery(document.body).append('<span class="game-status-alert">You Lose!</span>');

That works nicely, the problem comes when I want to create some slightly more advanced UI elements, specifically using angular. For example something like:

这很好用,当我想创建一些稍微高级的 UI 元素时,问题就出现了,特别是使用 angular。例如类似的东西:

function ChatBoxControl($scope) { /* Stuff */ }

jQuery(document.body).append(
    '<div ng-controller="ChatBoxControl"><div ng-repeat="line in chat"><span>{{line}}</span></div></div>'
);

Not surprisingly, this does not create a new angular view. It simply adds that html to the document and never binds to the ChatBoxControl.

毫不奇怪,这不会创建新的角度视图。它只是将该 html 添加到文档中,而不会绑定到 ChatBoxControl。

How can I achieve what I'm trying to do here?

我怎样才能在这里实现我想要做的事情?

回答by Artem Andreev

You should $compiledynamically added angular content. Something like:

您应该$compile动态添加的角度内容。就像是:

jQuery(document.body).append(
    $compile(  
        '<div ng-controller="ChatBoxControl"><div ng-repeat="line in chat"><span>{{line}}</span></div></div>'
    )(scope)
);

scope for any element you can get using something like:

您可以使用以下内容获得的任何元素的范围:

var scope = angular.element('#dynamicContent').scope();

Also you should get $compile that can be injected in other controller.

你也应该得到可以注入其他控制器的 $compile 。

See also: AngularJS + JQuery : How to get dynamic content working in angularjs

另请参阅:AngularJS + JQuery:如何在 angularjs 中获取动态内容

回答by Tosh

You might want to use ng-include combined with ng-repeat. Here is an simple example: http://plunker.no.de/edit/IxB3wO?live=preview

您可能希望将 ng-include 与 ng-repeat 结合使用。这是一个简单的例子:http: //plunker.no.de/edit/IxB3wO?live=preview

  <div ng-repeat="dom in domList" ng-include="dom"></div>

Parent $scope will keep the list of partials loaded into the view. And ng-repeat + ng-include will iterate over and display partials according to the list.

父 $scope 将保留加载到视图中的部分列表。并且 ng-repeat + ng-include 将根据列表迭代并显示部分。

When it is the right timing, you can append the partial into the dom list. e.g.

当时机合适时,您可以将部分附加到 dom 列表中。例如

$scope.domList.push("chatbox.html");

(BTW, putting DOM manipulation into controller is not the angular way.)

(顺便说一句,将 DOM 操作放入控制器不是角度方式。)