[英]Data binding inside AngularJs directive
在創建指令時,我很難弄清楚如何確保我保持雙向數據綁定。 這是我正在與之合作的小提琴:
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時,模型不會像我需要的那樣更新。 我究竟做錯了什么?
那么,雙向數據綁定不起作用有兩個原因。 首先,您需要在本地范圍屬性和父范圍屬性之間創建雙向綁定:
scope: { bar: "=ngModel" }
否則你要創建一個孤立的范圍(參見http://docs.angularjs.org/guide/directive )。
另一個原因是你必須用父項的追加替換后插入指令(因為你只是在dom.ready上引導角度):
element.parent().append(counterElement);
更新jsfiddle: http : //jsfiddle.net/andregoncalves/ksb3j/9/
你真的需要一個自定義指令嗎? AngularJS附帶一個與ngChange
結合使用的ngMaxlength
指令可能會對您有所幫助。
例如,如果您有以下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>
然后你只需要這個進入你的控制器
function foo($scope) {
$scope.change = function(){
if($scope.bar){
$scope.left = 20 - $scope.bar.length;
}else{
$scope.left = "";
}
};
$scope.bar = 'Hello';
$scope.change();
}
讓角度盡可能多地處理dom。
這是更新的jsfiddle: http : //jsfiddle.net/jaimem/ksb3j/7/
我不完全確定,但我認為你想要的是一個過濾器,看看這個網址,也許這是一個重新思考你的問題的好方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.