简体   繁体   English

AngularJS-在JS外部文件或HTML中包含代码?

[英]AngularJS - include code in outside JS file or within the HTML?

I have just started learning AngularJS and when I normally do jQuery applications I place all the Javascript in outside files. 我刚刚开始学习AngularJS,通常当我使用jQuery应用程序时,我会将所有Javascript放在外部文件中。 However, most of the examples for AngularJS I see the code placed in script tags at the bottom of the HTML page. 但是,在AngularJS的大多数示例中,我都在HTML页面底部的script标签中看到了代码。

I'm faced with the issue of PHP loading variables on the page and using AngularJS to reference those variables by placing them in a hidden tag and grab it or place the code at the bottom in a script tag. 我面临的问题是,PHP在页面上加载变量并使用AngularJS通过将它们放在隐藏标签中并抓住它或将代码放在脚本标签底部的方式来引用这些变量。

What is the most professional/common method of dealing with this issue? 解决此问题的最专业/最常用的方法是什么?

FYI: I do not want to enable PHP in JS files. 仅供参考:我不想在JS文件中启用PHP。

Thanks for your help, 谢谢你的帮助,

Cameron. 卡梅伦

Any examples that include the actual script in a script tag are done purely for review convenience to be able to see how angular components and view interact together. 在脚本标签中包含实际脚本的任何示例都是为了方便查看而完成的,以便能够查看角度分量和视图如何相互作用。

The norm is to use external file(s). 规范是使用外部文件。

There is a difference however with any script tag that is used to hold an html template. 但是,用于保存html模板的任何脚本标签都有所不同。

These tags will have the following type and do need to be in main file 这些标记将具有以下type并且确实需要在主文件中

 <script type="text/ng-template" id="/view1.tpl">
       <div>Some view template html</div>
 </script>

The ID for these template tags will equate to any templateUrl used in directives, routes or ng-include 这些模板标记的ID等于指令,路由或ng-include使用的任何templateUrl

The script tag examples are purely for brevity. 脚本标签示例纯粹是为了简洁。 I would personally never put a script tag into production code, it is too easily overlooked. 我个人永远不会在生产代码中添加脚本标记,这很容易被忽略。 There is a lot to be said for good file structure. 好的文件结构有很多要说的。

Echoing variables into your mark up with PHP is not a good way to go IMO. 在PHP中使用变量来标记变量并不是采用IMO的好方法。

It is much better practice to expose a web API and have your Angular app hit the endpoints asynchronously for any required data using the $http service. 更好的做法是公开一个Web API,并使用$http服务让Angular应用异步访问端点以获取任何所需数据。

If you are working on a production web application serving static markup and scripts that in turn access a separate API is a much more desirable architecture. 如果您正在使用提供静态标记和脚本的生产Web应用程序,而这些脚本又可以访问单独的API,则是更理想的体系结构。

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

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