当我创建指令时,我很难弄清楚如何确保我保持双向数据绑定。这是我正在使用的东西和小提琴:
http://jsfiddle.net/dkrotts/ksb3j/6/
HTML:
<textarea my-maxlength="20" ng-model="bar"></textarea>
<h1>{{bar}}</h1>
指示:
myApp.directive('myMaxlength', ['$compile', function($compile) {
return {
restrict: 'A',
scope: {},
link: function (scope, element, attrs, controller) {
element = $(element);
var counterElement = $compile(angular.element('<span>Characters remaining: {{charsRemaining}}</span>'))(scope);
element.after(counterElement);
scope.charsRemaining = parseInt(attrs.myMaxlength);
scope.onEdit = function() {
var maxLength = parseInt(attrs.myMaxlength),
currentLength = parseInt(element.val().length);
if (currentLength >= maxLength) {
element.val(element.val().substr(0, maxLength));
scope.charsRemaining = 0;
} else {
scope.charsRemaining = maxLength - currentLength;
}
scope.$apply(scope.charsRemaining);
}
element.keyup(scope.onEdit)
.keydown(scope.onEdit)
.focus(scope.onEdit)
.live('input paste', scope.onEdit);
element.on('ngChange', scope.onEdit);
}
}
}]);
当我在文本区域中输入时,模型并没有像我需要的那样更新。我究竟做错了什么?