頁面部分大致如下:
<body ng-app="PRoductManagement"> ... <div ng-include="'app/products/productListView.html'"></div> ...</body>
productManagement是頁面module的名稱。頁面內容通過ng-include加載productListView.html這個頁面。注意:ng-include屬性值是字符串'app/products/productListView.html', 而不是app/products/productListView.html,這點很容易疏忽。
頁面部分的javaScript引用順序通常是:有關AngularJS的文件、頁面級別的js文件、自定義有關Service的js文件、具體有關controller的js文件,就像這樣:
<!-- Library Scripts --><script src="scripts/angular.js"></script><script src="Scripts/angular-resource.js"></script><!-- application Script --><script src="app/app.js"></script><!-- Services --><script src="common/common.service.js"></script><script src="common/productResouce.js"></script><!-- Product Controllers --><script src="app/products/productListCtrl.js"></script>
在common.service.js中,定義了一個module:
(function () { "use strict"; angular.module("common.services", ["ngResource"]) .constant("appSettings", { serverPath: "http://localhost:49705/" });}());
以上,common.services這個module,依賴ngResource這個module,而ngResource這個module是被封裝在angular-resource.js文件中的,由此,把有關AngularJS的文件放在頂部是有道理的,否則common.services這個module就引用不到了。另外,common.services這個module還定義了一個常量,key是appSettings, value是一個object對象,該對象的serverPath存儲固定域名。
接下來,通過productResouce.js文件,自定義一個factory,用來返回具體的API路徑。
(function () { "use strict"; //通過工廠的方式創建了一個服務 angular.module("common.services") .factory("productResource", ["$resource", "appSettings", productResouce]); function productResouce($resource, appSettings) { return $resource(appSettings.serverPath + "/api/products/:id"); }}());
以上,為common.services這個module增加了一個factory,返回經$resource封裝的API路徑。同樣$resource這個服務來自于,angular-resource.js文件,再次體會到把有關AngularJS的文件放在頂部是有道理的。
好,有了module,注冊了factory,productListCtrl.js就來使用它們。
(function () { "use strict"; angular .module("productManagement") .controller("ProductListCtrl", ProductListCtrl); function ProductListCtrl(productResource) { var vm = this; productResource.query(function (data) { vm.products = data; }); }}());
以上,通過factory注冊的service注入到這里,調用productResource.query方法把數據加載到model中來。
然后,productListView.html這個頁面使用ProductListCtrl這個controller。
<div class="panel panel-primary" ng-controller="ProductListCtrl as vm"> <div class="panel-heading" style="font-size:large"> Product List </div> <div class="panel-body"> <table class="table"> <thead> <tr> <td>Product</td> <td>Code</td> <td>Available</td> <td>Price</td> </tr> </thead> <tbody> <tr ng-repeat="product in vm.products"> <td>{{ product.productName}}</td> <td>{{ product.productCode }}</td> <td>{{ product.releaseDate | date }}</td> <td>{{ product.price | currency }}</td> </tr> </tbody> </table> </div></div>
在頁面級別的app.js文件中是這樣的:
(function () { "use strict"; var app = angular.module("productManagement", ["common.services"]);}());
以上,productManagement依賴于自定義的common.services這個moduel。
總結:
1、js的位置關系要養成好的習慣:AngularJS文件,頁面文件,自定義service文件,controller文件
2、把請求API的邏輯封裝到自定義modlue中去,通過factory方式自定義service,使用$resouce來封裝API請求路徑
3、把自定義的service注入到controller中,請求API數據給Model
4、在主頁面的module注冊所有依賴的module
| 
 
 | 
新聞熱點
疑難解答