1
什麼時候應該在爲視圖轉換數據時引入ngModelController。$ formatter的複雜性?
換句話說,在以下(做作)的例子中,capitalizerA比capitalizerB更好嗎? 'A'感覺更習慣,但我很難找到明顯的優勢。
var app = angular.module('capitalizerApp', [])
app.controller('capitalizerCtrl', function($scope) {
$scope.name = 'jake';
});
/*
* capitalizerA
*/
app.directive('capitalizerA', function() {
return {
restrict: 'E',
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
let _capitalizerFormatter = function(value) {
return value.toUpperCase();
}
ngModelCtrl.$formatters.push(_capitalizerFormatter);
ngModelCtrl.$render = function() {
scope.capsName = ngModelCtrl.$viewValue;
}
}
}
});
/*
* capitalizerB
*/
app.directive('capitalizerB', function() {
return {
restrict: 'E',
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
ngModelCtrl.$render = function() {
scope.capsName = scope.name.toUpperCase();
}
}
}
})
請參見下面的工作例如:http://codepen.io/telekid/pen/oxNxPM?editors=1010