简体   繁体   English

如何使用javascript动态加载angularjs“ng-app”?

[英]How to load angularjs "ng-app" dynamically using javascript?

I created an web application in javascript and jQuery.我用 javascript 和 jQuery 创建了一个 web 应用程序。 Rendered dynamic html page using jQuery .load() method.使用 jQuery .load()方法呈现动态 html 页面。

File home.html, included angularjs.min.js file.文件 home.html,包括 angularjs.min.js 文件。 This page having one button "loadUsers".此页面有一个按钮“loadUsers”。 On click handler of the button loading "userList.html" file in a container ("#userContainer") same page.在容器(“#userContainer”)同一页面中加载“userList.html”文件的按钮的单击处理程序。

The userList.html sample content is like below, userList.html 示例内容如下所示,

<div ng-app>
Enter Your Name: <input type="text" ng-model="txtName" /> <br />
Hello {{txtName}}

On input, the value is not binding with model.在输入时,该值不与模型绑定。 Angular is not applied for dynamically loaded template. Angular 不适用于动态加载的模板。

Any one guide me how to achieve this?任何人指导我如何实现这一目标?

The AngularJS framework scans the DOM for the ng-app directive at DOMContentLoaded . AngularJS 框架在DOMContentLoaded处扫描 DOM 中的ng-app指令。 If the directive is added later (say after an .ajax call), the directive is ignored.如果该指令是稍后添加的(比如在.ajax调用之后),则该指令将被忽略。

Any apps added to the DOM after DOMContentLoaded need to be manually bootstrapped:DOMContentLoaded之后添加到 DOM 的任何应用程序都需要手动引导:

angular.bootstrap(document, ['myNgApp']);

For more information, see有关更多信息,请参阅


AngularJS and jQuery can live together if done wisely.如果做得好,AngularJS 和 jQuery 可以共存。 In fact the AngularJS framework will use jQuery internally if the jQuery library is loaded before the AngularJS library.事实上,如果 jQuery 库在 AngularJS 库之前加载,AngularJS 框架将在内部使用 jQuery。

For more information, see - AngularJS angular.element Function API Reference .有关更多信息,请参阅 - AngularJS angular.element函数 API 参考

The main question is: Why do you need to use jquery and angular together?!主要问题是:为什么需要同时使用jquery和angular?!

I think you can move the ng-app to body or html tag.我认为您可以将 ng-app 移动到 body 或 html 标签。 When the content is loaded use $compile service to append $scope to your view.加载内容后,使用 $compile 服务将 $scope 附加到您的视图中。 (angular 1.7) (角 1.7)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM