私は、分離スコープとngModelディレクティブを使用するディレクティブを作成しようとしています。孤立スコープとngモデルのディレクティブ
問題:
モデルがディレクティブで更新されると、呼び出し元の値が更新されません。
HTML:
<test-ng-model ng-model="model" name="myel"></test-ng-model>
が指令:
app.directive(
'testNgModel', [
'$timeout',
'$log',
function ($timeout, $log) {
function link($scope, $element, attrs, ctrl) {
var counter1 = 0, counter2 = 0;
ctrl.$render = function() {
$element.find('.result').text(JSON.stringify(ctrl.$viewValue))
}
$element.find('.one').click(function() {
if ($scope.$$phase) return;
$scope.$apply(function() {
var form = angular.isObject(ctrl.$viewValue) ? ctrl.$viewValue : {};
form.counter1 = ++counter1;
ctrl.$setViewValue(form);
});
});
$element.find('.two').click(function() {
if ($scope.$$phase) return;
$scope.$apply(function() {
var form = angular.isObject(ctrl.$viewValue) ? ctrl.$viewValue : {};
form.counter2 = ++counter2;
ctrl.$setViewValue(form);
});
});
$scope.$watch(attrs.ngModel, function (current, old) {
ctrl.$render()
}, true)
}
return {
require: 'ngModel',
restrict: 'E',
link: link,
//if isolated scope is not set it is working fine
scope: true,
template: '<div><input type="button" class="one" value="One"/><input type="button" class="two" value="Two"/><span class="result"></span></div>',
replace: true
};
}]);
デモ:fiddle
'スコープ:true'には、分離株のスコープを作成しません、それは、prototypically親スコープから継承する新しい子スコープを作成し、したがって、 '$ parent.model'の理由が働きます。 (分離スコープは 'scope:{...} '構文を使用するときに作成されます。ここでは新しい子スコープも作成されますが、プロトタイプ的に継承しません)。他のディレクティブ(つまり、ng-model)とやり取りする必要のあるコンポーネントを作成しているので、ng-modelで使用されます。だから、私はあなたの2番目の、働く、バイブルと一緒に行くことをお勧めします。 –
@MarkRajcokは、ディレクティブがより複雑で親スコープの汚染につながるカスタム属性をスコープに追加するので、私にとってはオプションではありません。 –
'scope:true'を使用しますが、プリミティブではありません: '' [フィドル](http://jsfiddle.net/mrajcok/6ZaB5/)。 –