2016-12-21 17 views
1

我想更好地瞭解如何連接應用程序的不同部分。我現在試圖找出如何將我的角度應用程序連接到我的HTML文件,如果文件在不同的文件夾中。我的文件夾結構是這樣的:如何將角度應用連接到您的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中,我也會得到這樣的錯誤:需要的錯誤沒有被定義,但是如果express不能被需要,那麼它應該如何被使用?

我看着使用browserify來解決錯誤的要求,但我的頁面加載時間的方式。感謝您的幫助。我知道有很多工具可以完成像yeomen generator這樣的引導工作,但我想從頭開始理解如何做到這一點。 Github上鍊接:https://github.com/sbernheim4/pomodoro-timer

回答

1

的幾個問題。一般來說,您會將節點使用的文件混淆爲應用服務器的一部分,以提供網頁和將在用戶瀏覽器中加載的JavaScript。一旦記住將這兩者分開,就會變得更容易理解。

  1. 我該如何讓我的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庫,並且可以將其包含,你是包括以同樣的方式index.js

  2. 此外,即使在index.js我得到的錯誤,需求沒有定義,但如果表達不能要求那麼它應該如何使用?

    這裏要記住的是index.js是你的服務器的一部分(因此,不應該在public目錄中)。這意味着您不在HTML中包含index.js。相反,您使用node /path/to/index.js啓動節點來啓動您的網絡服務器。保持你的服務器端腳本與你的HTML分開,並且你會很開心!請記住,您在服務器端使用節點語義,並且在腳本/ HTML中使用瀏覽器JavaScript語義。你不包括你的服務器端JS在你的index.html中。

+0

好的,明白了。非常感謝。這現在變得更有意義 – sam4444

0

在HTML模板,應該說在您的文章

<body ng-app='pomodoro-timer'> 
     <p>{{message}}</p> 
</body> 
+0

謝謝!接得好。 – sam4444

+0

nmusleh爲什麼它應該是小寫,如果當我宣佈我的角應用程序爲: var app = angular.module('PomodoroTimer',[]); 約定是隻聲明小寫還是角度改變它? – sam4444

相關問題