在 AngularJS 中,若需要在多個 controller 之間共用同一份設定或狀態,直覺的做法是宣告一個全域變數,但這在架構上並不理想。AngularJS 本身提供了更合適的機制。以下整理三種可行方式,並說明各自的適用時機。
目標很明確:在 ng-app 中定義的變數,要能在不同的 ng-controller 裡被讀取。
這與純 JavaScript 完全相同,把變數宣告在 app 模組的檔案頂層,由於同一作用域內的各 controller 都能存取到它,因此到處都讀得到。缺點也很明顯:它繞過了依賴注入,不利於測試與維護,變數名稱也容易污染全域。
value 用來註冊一個簡單的值(字串、數字、物件皆可),註冊後可以透過注入使用。
constant 的用法與 value 幾乎相同,差別在於 constant 可以在模組的 config 階段就被注入,而 value 不行。因此 apikey、API 位址這類需要在路由設定時就取用的值,該用 constant。
1. 在 app 模組中定義
'use strict';
/* App Module */
var test2 = 'tank'; // 方法一:純 JS 全域變數
var phonecatApp = angular.module('phonecatApp', [
'ngRoute',
'phonecatControllers',
'tanktest'
]);
phonecatApp.value('test', { "test": "test222", "test1": "test111" }); // 方法二
phonecatApp.constant('constanttest', 'this is constanttest'); // 方法三
phonecatApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/phones', {
templateUrl: 'partials/phone-list.html'
// 這裡沒有指定 controller,可在模板中加上 ng-controller
})
.when('/phones/:phoneId', {
templateUrl: 'partials/phone-detail.html',
controller: 'PhoneDetailCtrl'
})
.when('/login', {
templateUrl: 'partials/login.html',
controller: 'loginctrl'
})
.otherwise({ redirectTo: '/login' });
}]);
2. 在 controller 中注入使用
'use strict';
/* Controllers */
var phonecatControllers = angular.module('phonecatControllers', []);
phonecatControllers.controller('PhoneListCtrl',
['$scope', 'test', 'constanttest',
function ($scope, test, constanttest) {
$scope.test = test; // 方法二
$scope.constanttest = constanttest; // 方法三
$scope.test2 = test2; // 方法一
}]);
3. 在 HTML 中呈現
<div data-ng-controller="PhoneListCtrl">
{{test.test1}} {{constanttest}} {{test2}}
</div>
輸出結果:test111 this is constanttest tank
實務上的建議是:避免方法一,並依需求在 value 與 constant 之間選擇;若資料會變動(例如使用者設定、購物車內容),更合適的做法其實是 factory 或 service——它們回傳的是一個物件,天然適合用來保存狀態,也方便注入與測試。
換句話說,value 與 constant 適合放「不變的設定」,factory 與 service 適合放「會變的狀態」。把這條界線畫清楚,AngularJS 專案的架構就不容易腐化。