AngularJS 的 ngModel 提供了「模型 ↔ 畫面」的雙向轉換掛勾,分別是 $formatters(模型 → 畫面)與 $parsers(畫面 → 模型)。本文用一個「畫面上用逗號分隔、模型裡是陣列」的例子,示範如何寫出自訂的 input 指令。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>input 指令示例</title>
</head>
<script src="js/jquery.js"></script>
<script src="js/angular.min.js"></script>
<body ng-app="Demo">
<div ng-controller="TestCtrl">
<input type="text" ng-model="a" test />
<button ng-click="show(a)">查看</button>
</div>
<script>
var app = angular.module('Demo', [], angular.noop);
app.directive('test', function(){
// input 指令的 link 有第四個參數 $ctrl,裡面有些方法可以拿來用
var link = function($scope, $element, $attrs, $ctrl){
console.log($ctrl);
// 模型 → 畫面:陣列變成逗號字串
$ctrl.$formatters.push(function(value){
return value.join(',');
});
// 畫面 → 模型:逗號字串變成陣列
$ctrl.$parsers.push(function(value){
return value.split(',');
});
}
return {
compile: function(){ return link },
require: 'ngModel',
restrict: 'A'
}
});
app.controller('TestCtrl', function($scope){
$scope.a = [];
//$scope.a = [1, 2, 3];
$scope.show = function(v){
console.log(v);
}
});
</script>
</body>
</html>
這是最容易混淆的地方,記法很簡單:formatter 是「格式化出去」,資料從 model 往 view 流動時經過它,所以 $formatters 的函式回傳字串;parser 是「解析進來」,使用者輸入後資料從 view 往 model 流動,所以 $parsers 的函式回傳模型值。
範例中 $scope.a 是陣列,畫面上呈現為 1,2,3,使用者改成 4,5,6 後點按鈕,console 印出的是陣列 [4, 5, 6]。這正是兩個掛勾協作的成果。
link 函式的第四個參數來自 require。要操作模型轉換,就必須 require: 'ngModel' 取得 NgModelController。少了它,$ctrl 會是 undefined。順帶一提,input 元素上必須有 ng-model,否則 ngModel 控制器根本不會建立。
兩者用 push 加入,代表可以串多個轉換函式,依註冊順序依序執行。實務上常見的組合是:一個 parser 做 trim、一個做型別轉換、一個寫入驗證狀態。要中斷整條鏈(例如驗證失敗不寫入 model),在函式中回傳 undefined 即可。
如果只是想在使用者輸入時觸發副作用,不需要動到資料格式,可以用更輕量的 $ctrl.$viewChangeListeners.push(fn)。而 $validate、$isEmpty 則是掛自訂驗證規則的位置。把 $formatters、$parsers、$validators、$viewChangeListeners 這四個掛勾搞熟,自訂表單控制項就沒有難題了。