AngularJS のディレクティブのテンプレート内の要素を使用して双方向バインディングを作成する方法がわかりません。
私の例:
HTML
<div ng-app="App">
<div ng-controller="AppCtrl">
<input ng-model="myValue" />{{myValue}}
<uppercase ng-model="myValue" />
</div>
</div>
Javascript
var app = angular.module('App', []);
function AppCtrl($scope) {
$scope.myValue = 'Hello World';
};
app.directive('uppercase', function() {
return {
restrict : 'E',
replace: true,
require: 'ngModel',
template: '<div><input ng-model="ngModel" /></div>', //If I remove the wrapping div, it works, but I have to change the ng-model attribute on the directive scope to be something else, such as 'model'
scope: {
ngModel: '=',
},
link: function(scope, element, attr, ngModel) {
function parse(string) { //with the div in the template function is never called
//alert('parsing');
//debugger;
return (string || '').toLowerCase();
}
function format(string) { //with the div in the template, string is always 'undefined' and the function is only called once
//alert('formatting');
//debugger;
return (string || '').toUpperCase();
}
ngModel.$parsers.push(parse);
ngModel.$formatters.push(format);
}
};
});
問題は、双方向バインディングが確立されているが、パーサーとフォーマッターが適切に呼び出されないことです。これらの関数に渡される値は常に「未定義」です。私の例は、バインドしたい要素がテンプレートの最も外側の要素である場合に機能しますが、子要素にバインドする必要があります。
リンク関数の ngModel パラメータの問題に絞り込んだと思います。私はディレクティブにあまり詳しくないので、そのコンテキストで ngModel オブジェクトが何であるかさえわかりません。
これをデバッグする助けがあれば幸いです。