Dobrym sposobem na to jest użycie dyrektywy. Oto jak może to być zrobione:
zobacz:
<div ng-app="foo" ng-controller="fooController">
<textarea text-length-handler="doThing()" text-length="6" ng-model="text">
</textarea>
</div>
JS:
angular.module('foo', [])
.directive('textLength', function(){
return {
restrict: 'A',
require: 'ngModel',
scope: {
textLengthHandler: '&'
},
link: function ($scope, $element, $attrs, ctrl) {
var limit = parseInt($attrs.textLength);
var handler = function(){
if (ctrl.$modelValue.length >= limit) {
$scope.textLengthHandler()
}
};
$element.on('keypress', handler);
// remove the handler when the directive disappears
$scope.$on('destroy', function(){
$element.off('keypress', handler)
});
}
}
})
Fiddle tutaj:
http://jsfiddle.net/dtq0mz8m/
nie działa, gdy naciśnięty jest spacja .. –
To byłaby łatwa poprawka, po prostu usuń wszystkie spacje z funkcji '$ scope.textChanged'. – JimmyBoh
Możesz również dodać 'ng-trim =" false "' do znacznika wejściowego, aby zapobiec automatycznemu przycinaniu białego spacji dla spacji. –