AngularJs指令里面的数据绑定 [英] Data binding inside AngularJs directive
问题描述
我有一个很难搞清楚如何确保我保持当我创建指令2路数据绑定。以下是我与工作和小提琴:
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>
指令:
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的输入,模型没有更新就像我需要它。我在做什么错了?
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" }
否则你创建一个孤立的范围(见 http://docs.angularjs.org/guide/directive )。
另外一个原因是,你必须从父追加插入指令后取代了(因为你只在dom.ready自举角):
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);
更新的jsfiddle:<一href=\"http://jsfiddle.net/andregoncalves/ksb3j/9/\">http://jsfiddle.net/andregoncalves/ksb3j/9/
这篇关于AngularJs指令里面的数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!