Reputation: 440
If you look at this fiddle: http://jsfiddle.net/rodhartzell/u4zVd/1/
You can see that the model $scope.bar is not accounted for by the directive, until one of the subscribed events is handled. Do you know of a way to make the directive recognize the model as soon as it binds?
element.keyup(scope.onEdit)
.keydown(scope.onEdit)
.focus(scope.onEdit)
.live('input paste', scope.onEdit);
element.on('ngChange', scope.onEdit);
Upvotes: 3
Views: 107
Reputation: 43745
I would have approached the whole issue differently. Rather than binding the event, I would setup a watch on the length like this:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.bar = 'something';
});
app.directive('myMaxlength', function($compile) {
return {
restrict: 'A',
scope: { bar: "=ngModel" },
link: function(scope, element, attrs) {
var counterElem = angular.element('<span>Characters remaining: {{charsRemaining}}</span>');
$compile(counterElem)(scope);
element.parent().append(counterElem);
scope.$watch(
function() {
return scope.bar.length;
},
function(newLength) {
scope.charsRemaining = attrs.myMaxlength - newLength;
}
);
}
};
});
Upvotes: 4