I am having a hard time figuring out how to make sure I maintain 2-way data binding when I create directives. Here is what I am working with and the fiddle:
http://jsfiddle.net/dkrotts/ksb3j/6/
HTML:
<textarea my-maxlength="20" ng-model="bar"></textarea>
<h1>{{bar}}</h1>
Directive:
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);
}
}
}]);
As I type in the textarea, the model is not updating like I need it to. What am I doing wrong?
Well, there are two reasons why the two-way databinding doesn't work. First, you need to create a bi-directional binding between a local scope property and the parent scope property:
scope: { bar: "=ngModel" }
otherwise you're creating an isolated scope (see http://docs.angularjs.org/guide/directive).
The other reason is that you have to replace the after insert instruction with an append from the parent (because you are only bootstrapping angular on dom.ready):
element.parent().append(counterElement);
Update jsfiddle: http://jsfiddle.net/andregoncalves/ksb3j/9/
Do you really need a custom directive? AngularJS ships with a ngMaxlength
directive that combined with ngChange
might help you.
For example, if you have the following HTML
<body ng-controller="foo">
<form name="myForm">
<textarea name = "mytextarea"
ng-maxlength="20"
ng-change="change()"
ng-model="bar"></textarea>
<span class="error" ng-show="myForm.mytextarea.$error.maxlength">
Too long!
</span>
<span> {{left}} </span>
<h1>{{bar}}</h1>
</form>
</body>
Then you just need this into your controller
function foo($scope) {
$scope.change = function(){
if($scope.bar){
$scope.left = 20 - $scope.bar.length;
}else{
$scope.left = "";
}
};
$scope.bar = 'Hello';
$scope.change();
}
Let angular handle the dom as much as you can.
Here's the updated jsfiddle: http://jsfiddle.net/jaimem/ksb3j/7/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With