我有這個$parser
這限制了用戶輸入的字符數:觸發AngularJS NG-模型管道的onblur
var maxLength = attrs['limit'] ? parseInt(attrs['limit']) : 11;
function fromUser(inputText) {
if (inputText) {
if (inputText.length > maxLength) {
var limitedText = inputText.substr(0, maxLength);
ngModel.$setViewValue(limitedText);
ngModel.$render();
return limitedText;
}
}
return inputText;
}
ngModel.$parsers.push(fromUser);
我想利用這個指令,它有ng-model-options="{updateOn: 'blur'}"
輸入元素,但有一個在用戶失去輸入元素的焦點後,整個$parser
事件被執行的問題,我希望它在用戶鍵入到輸入字段時執行。
(function (angular) {
"use strict";
angular.module('app', [])
.controller("MainController", function($scope) {
$scope.name = "Boom !";
$scope.name2 = "asdf";
}).directive('limitCharacters', limitCharactersDirective);
function limitCharactersDirective() {
return {
restrict: "A",
require: 'ngModel',
link: linkFn
};
function linkFn(scope, elem, attrs, ngModel) {
var maxLength = attrs['limit'] ? parseInt(attrs['limit']) : 11;
function fromUser(inputText) {
if(inputText) {
if (inputText.length > maxLength) {
var limitedText = inputText.substr(0, maxLength);
ngModel.$setViewValue(limitedText);
ngModel.$render();
return limitedText;
}
}
return inputText;
}
ngModel.$parsers.push(fromUser);
}
}
})(angular);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<div ng-app="app">
without ng-model-options: <input type="text" ng-model="name" limit-characters limit="7" />
<br>
with ng-model-options <input type="text" ng-model="name2" ng-model-options="{updateOn: 'blur'}" limit-characters limit="7" />
</div>
寫得很好,但我有一個問題與新指令,當用戶複製並粘貼到指令,它不會注意到它。任何想法? – Rachmaninoff