我试图更好地了解如何连接应用程序的不同部分。我现在试图找出如何将我的角度应用程序连接到我的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并加载我的角度应用程序。当我尝试使用脚本标签时,如我加载index.js,我会收到一个错误,说require是未定义的,因为它只能在服务器上使用而不能在浏览器上使用?此外,即使在index.js中,我得到的错误仍然没有定义,但如果不能表达,那么应该如何使用?
我研究了使用browserify来解决错误问题,但是我的页面的加载时间开始上升了。谢谢你的帮助。我知道有很多工具可以像yeomen生成器一样完成所有这些引导,但我想从头开始了解如何自己完成这项工作。 Github链接:https://github.com/sbernheim4/pomodoro-timer
答案 0 :(得分:1)
您帖子中的几个问题。一般来说,您将节点作为appserver的一部分用于提供网页的文件和将在用户浏览器中加载的javascript混淆。一旦你记得将这两者分开,就会更容易理解。
我怎样才能使我的index.html文件引用我的app.js并加载我的角度应用程序。当我尝试使用脚本标签时,如我加载index.js,我会收到一个错误,说require是未定义的,因为它只能在服务器上使用而不能在浏览器上使用?
这是正确的 - 现在require
仅用于服务器端而不是浏览器(除非您使用的是AMD / require.js / bowserify)。要使用angular
关键字,只需在脚本中使用angular
,而不需要:
'use strict'
// var angular = require('angular');
var app = angular.module('PomodoroTimer', []);
包含角度js库后,angular关键字可全局使用,您可以按照与index.js
相同的方式包含它。
此外,即使在index.js中,我得到的错误仍未定义,但如果不能表达,那么它应该如何使用呢?
这里要记住的是index.js是服务器的一部分(因此,不应该在public
目录中)。这意味着您不要在HTML中包含index.js
。相反,您使用node /path/to/index.js
启动网络服务器来启动节点。保持服务器端脚本独立于HTML之外,你会很高兴!请记住,您在服务器端使用节点语义,并在脚本/ HTML中使用浏览器javascript语义。您没有在index.html中包含服务器端JS。
答案 1 :(得分:0)
在HTML模板中,应该说
<body ng-app='pomodoro-timer'>
<p>{{message}}</p>
</body>