我們近期為論壇專業人員首頁新增了一項自動完成功能(稱為 Smarty),這項功能能引導使用者快速找到想要的內容,極大地提升了導航體驗。整個元件基於 AngularJS 打造,作為我初次接觸該框架的專案,過程中獲得了寶貴的實戰經驗,也深刻體會到 AngularJS 的模組化設計如何優雅地滿足複雜的互動需求。
Smarty 需滿足以下關鍵特性:
AngularJS 將功能拆解為具備明確職責的核心概念——Directive(指令)與 Service(服務)。Directive 負責 DOM 綁定與元素互動管理,Service 則透過依賴注入為 Controller 與 Directive 提供可重用的獨立邏輯。專案廣泛運用內建指令如 ngIf、ngRepeat 條件渲染下拉清單,ngModel 雙向綁定輸入值,並搭配 $watch 監聽前綴變化觸發請求。
面對使用者輸入速度可能超過請求回應的挑戰,我們利用 $http 服務的可選快取參數:$http.get(requestUrl, {cache: true}),輕鬆實現回應快取,顯著降低伺服器負載並提升介面流暢度。
封裝 getSmartySuggestions(prefix) 方法,接收前綴參數呼叫後端建議 API,回傳 Promise 物件,支援鏈式處理非同步流程。
集中管理使用者與下拉清單的所有互動邏輯(鍵盤導航、滑鼠懸停/點擊、外部點擊關閉等),配合內建 ng-mouseover、ng-click 處理滑鼠事件。為確保互動邏輯穩健,我們引入 Jasmine 測試框架搭配 angular-mocks 編寫詳細測試案例,如「點擊外部應關閉清單」、「按 Enter 回填選中值」等,保障開發迭代品質。
在學習過程中,隔離作用域綁定符號與 Promise 是兩大難點。以下針對三種綁定模式提供實戰範例:
// Controller
$scope.selected = -1;
// HTML
<input index="selected" smarty-input />
// Directive
scope: { index: "=", ... }
將 Controller 的 selected 與 Directive 內部 index 雙向同步,使用者鍵盤操作導致的索引變化會即時傳播回 Controller。
// Controller
$scope.setSelected = function(newValue) { ... };
// HTML
<input smarty-input select="setSelected(x)" />
// Directive
scope: { select: "&", ... }
scope.select({ "x": parseInt(scope.index) + 1 });
Directive 可呼叫 Controller 定義的函式,且不直接修改其實作,符合關注點分離原則。
// Controller
$scope.prefix = "";
// HTML
<div smarty-suggestions prefix="{{prefix}}"></div>
// Directive
scope: { prefix: "@", ... }
適用於將插值表達式作為字串傳遞,常用於複雜表達式如 next-index="{{selected + 1}}"。
Promise 透過 then() 註冊回調處理非同步結果。Smarty 中流程如下:
$scope.$watch 偵測 $scope.prefix 變化,呼叫 getSmartySuggestions()$http.get 回傳 Promise,then() 中解析回應資料(取前 5 筆 Name 陣列)並返回新 Promise$scope.suggestions 觸發視圖重渲染// Service
function getSmartySuggestions(prefix) {
requestParams["query"] = escape(prefix.toLowerCase());
return $http.get(requestUrl(), { params: requestParams, cache: true })
.then(function(response) {
return response.data.slice(0, 5).map(function(item) { return item.Name; });
});
}
// Controller
var promise = smartySuggestor.getSmartySuggestions($scope.prefix);
promise.then(function(data) { $scope.suggestions = data; });

透過這個專案,不僅完成了功能豐富的自動完成元件,更建立了對 AngularJS 核心機制的深度理解,為後續大型應用開發奠定堅實基礎。