ディレクティブの ng-model を介してコントローラー スコープから値を渡す独自のモデルを持つテキスト入力を含む AngularJS ディレクティブがあります。
このペン (および以下のコード) をチェックしてください: http://codepen.io/ericwshea/pen/KwXRyr
問題は、そのモデルがたまたま null または未定義の値になる場合があることです。その場合、テキスト入力の ngModelController を使用して、テキスト入力の null 値の表示を「NULL」のようにフォーマットします。
値がフォーマッタで一致する任意の文字列である場合は機能しますが、値が null の場合は機能しません (未定義の同じ結果でもテストしました)。
これに関する洞察/回避策、またはこれは単なる $formatters の欠点ですか?
HTML:
<div ng-app="app" class="container">
<div ng-controller="ctrl" class="col-md-12">
<form>
<input-directive ng-model="model"></input-directive>
<input-directive ng-model="model2"></input-directive>
<div ng-if="model">Model 1: {{model}}</div>
<div ng-if="model2">Model 2: {{model2}}</div>
</form>
</div>
</div>
ジャバスクリプト:
angular.module('app', [])
.controller('ctrl', function($scope) {
$scope.model = null;
$scope.model2 = 'make this null';
})
.directive('inputDirective', function() {
var template =
'<div>'+
'<div class="input-group">'+
'<input type="text" class="form-control" ng-model="localModel">'+
'<span class="input-group-btn">'+
'<button ng-click="save()" class="btn btn-default" type="button">Save</button>'+
'</span>'+
'</div>'+
'</div>';
function link (scope, elem, attr) {
var inputModelCtrl = elem.find('input').controller('ngModel');
function formatter(val) {
if (val === 'make this null') {
return scope.nullValue;
}
if (val === null) {
return scope.nullValue;
}
return val;
}
scope.nullValue = 'NULL';
scope.localModel = scope.ngModel;
scope.save = function() {
scope.ngModel = scope.localModel;
}
inputModelCtrl.$formatters.push(formatter);
}
return {
restrict: 'E',
replace: true,
require: 'ngModel',
template: template,
link: link,
scope: {
ngModel: '='
}
}
})
;