我很難搞清楚如何確保在創建指令時保持雙向數據綁定。以下是我與工作和小提琴:AngularJs指令中的數據綁定
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);
}
}
}]);
正如我在textarea的種,型號沒有更新就像我需要它。我究竟做錯了什麼?
我不認爲這是我在這裏遇到的困難。我的問題非常簡單。在textarea上,我分配了一個模型。啓用myMaxlength指令後,該模型上的雙向綁定正在打破。 – Dustin