テキスト型の入力を含むテンプレートをビューに追加するディレクティブを作成しています。このディレクティブでは、テキスト フィールド入力が指定された最大長設定を超えている場合にエラー通知用にスパン クラスを追加しようとしています。次のようなコードがあります。
<div ng-app="app">
<form name="userForm" ng-submit="processForm()" novalidate>
<div use-text-box name="xyz" ng-maxlength="10" required> </div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>
私のディレクティブは次のようになります。
var app = angular.module('app', []);
app.directive('useTextBox', function() {
return {
replace:true,
compile: function(element,attrs) {
var name = attrs.name;
var maxLengthError = attrs.hasOwnProperty('ngMaxlength') ? '<span ng-show="userForm.' + attrs.name + '.$error.maxlength" class="help-block">Text is too long. The limit is ' + attrs.ngMaxlength + ' characters.</span>' : '';
var htmlText = '<input type="text" name="' + name + '" ng-maxlength="' + attrs.ngMaxlength + '" required />' +
maxLengthError;
element.replaceWith(htmlText);
}
};
});
しかし、上記のコードでは、ディレクティブは入力テキスト フィールドなどを生成しています。問題はありません。ただし、最大長が 10 を超える場合、エラー メッセージは表示されません。何が間違っていますか?
上記の例の jsfiddle へのリンクは次のとおりです: http://jsfiddle.net/fB45J/3/