標籤:
本篇體驗AngularJS的Hello World,雖然簡單,但體現了AnuglarJS的一些重要概念。
大致思路是這樣的:
- 通常通過為html元素添加AngularJS專屬的屬性來實現一些功能,比如ng-app, ng-controller
- 在js中,通常需要註冊一個module,然後為module再註冊controller等。AngularJS不僅僅有angular.js檔案,還有其他的js檔案,比如用來做路由配置的angular-route.js檔案等。每一個檔案包含module,使用AnularJS的過程就是讓這些modules協同工作的過程
首先在頁面引入AngularJS的核心js檔案:
<script src="angular.min.js"></script>
接著,在定義js檔案中為當前頁面註冊一個module:
var myApp = angular.module("helloApp",[])
以上,module的名稱為helloApp, []數組用來存放與當前module有依賴關係的其它modules,比如[‘ngRoute‘,‘....‘]。
然後,為module註冊controller。
方式一,數組注釋法(array-style notation)
myApp.controller("TestController",[‘$scope‘,‘Project‘,function($scope,Project){ $scope.hello = "Hello World!"; }]);
以上,controller()的第一個參數是controller的名稱,第二個參數的數組,數組的最後一個元素一定是匿名函數,其它元素是AngularJS的全域service,或者說是全域對象。需要注意的是:數組中的全域service的位置和名稱必須和匿名函數的形參一一對應。
方式二,我們還可以這樣寫,簡單注入方式(Simple injection method)
myApp.controller("TestController", function($scope){ $scope.hello = "Hello World!"; });
AngularJs會掃描function的參數,提取參數的名稱(name)作為function的依賴。所以這種方式要求保證參數名稱的正確性,但對參數的順序並沒有要求。
不過,以上的寫法在給js檔案最佳化壓縮的時候,會改變$scope變數的名稱,比如替代為a,由於AngularJS只認$scope不認識a,這樣會導致報錯。所以,這種方法不推薦。第一種注入方式可以幫我們解決這個問題。
另外,全域service是以注入的方式被當前controller所使用。在AngularJS中,很多全域service都是通過依賴注入的方式被運用。
最後,頁面中要做3件事情。
1、使用ng-app聲明當前module的名稱
<html ng-app="helloApp">
2、使用ng-controller聲明需要使用的controller
<body ng-controller="TestController">
3、使用{{}}顯示$scope中的變數
<p>{{hello.name}}</p>
完整的代碼如下:
<!doctype html><html ng-app="helloApp"> <head> <meta charset="UTF-8"> <title>Untitled Document</title> <script src="angular.min.js"></script> <script> var myApp = angular.module("helloApp", []) myApp.controller("TestController", [‘$scope‘, function($scope) { $scope.hello = "Hello World!"; }]); </script> </head> <body ng-controller="TestController"> <p>{{hello}}</p> </body></html>
當然,實際項目中$scope變數通常用來儲存物件。比如:
var myApp = angular.module("helloApp", []) //聲明對象並對其賦值 var messages = {}; messages.name = ‘Hello World!‘; myApp.controller("TestController", [‘$scope‘, function($scope) { $scope.hello = messages; }]);
在頁面中按如下調用:
<p>{{hello.name}}</p>
當然與上面寫法等同是:
<p ng-bind="hello.name"></p>
AngularJS的Hello World