ある種の一般的な残りの機能を実現しようとしています。フォームには、名前と住所などのフィールドがたくさんあります。これらのフィールドには文字サイズの制限があります。私の目標は、到達したときにサイズを制限するジェネリック関数を作成することです。そこで、動作するサンプル関数を作成しました。
ページの最初:
label(for='name') Name {{remaining()}} of {{totalChars}}
次に、それを処理するコード:
$scope.totalChars = 10;
$scope.remaining = function() {
var count = 0;
if ($scope.mName) {
count = $scope.mName.length;
if (count > $scope.totalChars) {
$scope.mName = $scope.mName.trim().substr(0, $scope.mName.length - 1);
count = $scope.mName.length;
}
}
return count;
//return calculateChars($scope.mName, $scope.totalChars);
};
名前フィールドに入力値を入力すると、10文字に達するとangularは入力を停止します。しかし、私はそれを一般的な方法で回して、私が望む任意のフィールドにそれを使用しようとするように関数を作り直しましたが、期待どおりに機能しません:
$scope.totalChars = 10;
$scope.remaining = function() {
return calculateChars($scope.mName, $scope.totalChars);
};
..。
function calculateChars(obj, size) {
var count = 0;
if (obj && obj !== 'undefined') {
count = obj.length;
if (count > size) {
$scope.obj = obj.trim().substr(0, obj.length - 1);
console.log('Result: ' + $scope.obj);
count = obj.length;
}
}
return count;
}
部分性は問題なく機能します。calculateChars
問題は$scope.obj = obj.trim().substr(0, obj.length - 1);
、angularjsが「obj」が何であるかを認識せず、10文字に達しても入力を停止せず、量を正しくカウントしているためです。
必要なテキストフィールドのコードを複製せずに、最初のアプローチをどのような場合でも機能させる方法がわかりません。
前もって感謝します!