我正在尝试更好地理解如何连接应用程序的不同部分。我现在正在尝试弄清楚如何连接我的angular应用程序到我的html文件,如果文件在单独的文件夹中。我的文件夹结构是这样的:
|--Timer/
| -browser/
| -js/
| -app.js --> This is where I declare my angular app like var app = anguler.module('app', []);
| -scss/
| -server/
| -public/
| -index.js --> using ExpressJS to handle routing here. Essienntially just send all requests to index.html since I plan on eventually using the UI-Router from Anguler for state changes
| -index.css
| -index.html
这是我在app.js中的内容
'use strict'
var angular = require('angular'); //I don't know if this is the right way to use angular but otherwise I get an error saying angular is undefined. I have it installed through node as a dependency
var app = angular.module('PomodoroTimer', []);
app.controller('MainCtrl', function($scope) {
$scope.message = 'THIS IS A MESSAGE';
});
app.config(function($locationProvider) {
$locationProvider.html5Mode(true);
});
这是index.html
<!DOCTYPE html>
<html>
<head>
<!-- Custom css style sheet -->
<link rel="stylesheet" href="index.css">
<!-- Include Angular from google cdn -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript" src='index.js'> </script>
</head>
<body ng-app='PomodoroTimer'>
<p>{{message}}</p>
</body>
</html>
我怎样才能使index.html文件引用app.js并加载angular应用程序呢?当我尝试使用脚本标记(如如何加载index.js)时,我会收到一个错误消息,说“require is undefined”,因为它只能在服务器上使用,而不能在浏览器上使用。另外,即使在index.js中,我也会遇到“require is not defined”(未定义require)的错误,但是如果express不能被请求,那么它应该如何使用呢?
我研究了使用browserify来绕过require的错误,但是我的页面的加载时间却大大增加了。我知道有很多工具可以像自耕农生成器一样做所有这些引导,但是我想了解如何自己从头开始做这些。
GitHub链接:https://github.com/sbernheim4/pomodoro-timer
2条答案
按热度按时间dfty9e191#
你的帖子里有几个问题。一般来说,你把node作为应用服务器的一部分来提供网页的文件和用户浏览器中加载的javascript弄混了。一旦你记住把这两个分开,就更容易理解了。
1.如何使index.html文件引用app.js并加载angular应用程序?当我尝试使用脚本标记(如如何加载index.js)时,我会收到一个错误消息,称require未定义,因为它只能在服务器上使用,而不能在浏览器上使用?
这是正确的--目前
require
只在服务器端使用,而不在浏览器中使用(除非您使用的是AMD/require.js/bowserify之类的代码)。要使用angular
关键字,只需在脚本中使用angular
,而不使用require:一旦包含angular js库,angular关键字就可以全局使用,并且可以像包含
index.js
一样包含它。1.而且,即使在index.js中,我也会遇到这样的错误:require没有定义,但是如果express不能被要求,那么它应该如何使用呢?
这里要记住的是index.js是服务器的一部分(因此,它不应该在
public
目录中)。这意味着您不需要在HTML中包含index.js
。相反,您可以使用node /path/to/index.js
启动Web服务器来启动节点。将服务器端脚本与HTML分开,这样您就可以开始了!请记住:在服务器端使用节点语义,在脚本/HTML中使用浏览器javascript语义。在index.html中不包含服务器端JS。1aaf6o9v2#
在HTML模板中,它应该是