そのビューで親スコープを使用するディレクティブがあります。このディレクティブには、分離スコープを使用する子ディレクティブがあります。子ディレクティブの ngModel に加えられた変更を監視し、変更が加えられた場合は独自のモーダルを更新するように親ディレクティブを取得しようとしています。おそらくよりよく説明する jsfiddle があります: http://jsfiddle.net/Alien_time/CnDKN/
コードは次のとおりです。
<div ng-app="app">
<div ng-controller="MyController">
<form name="someForm">
<div this-directive ng-model="theModel"></div>
</form>
</div>
</div>
Javascript:
var app = angular.module('app', []);
app.controller('MyController', function() {
});
app.directive('thisDirective', function($compile, $timeout) {
return {
scope: false,
link: function(scope, element, attrs) {
var ngModel = attrs.ngModel;
var htmlText = '<input type="text" ng-model="'+ ngModel + '" />' +
'<div child-directive ng-model="'+ ngModel + '"></div>';
$compile(htmlText)(scope, function(_element, _scope) {
element.replaceWith(_element);
});
// Not sure how to watch changes in childDirective's ngModel ???????
}, // end link
} // end return
});
app.directive('childDirective', function($compile, $timeout) {
return {
scope: {
ngModel: '='
},
link: function(scope, element, attrs, ngModel) {
var htmlText = '<input type="text" ng-model="ngModel" />';
$compile(htmlText)(scope, function(_element, _scope) {
element.replaceWith(_element);
});
// Here the directive text field updates after some server side process
scope.ngModel = scope.dbInsertId;
scope.$watch('dbInsertId', function(newValue, oldValue) {
if (newValue)
console.log("I see a data change!"); // Delete this later
scope.ngModel = scope.imageId;
}, true);
},
} // end return
});
この例では、親ディレクティブとその子ディレクティブ内にテキスト入力があることがわかります。それらのそれぞれの中に入力すると、他のモデルはによってバインドされているため、更新されngmodel
ます。ただし、子ディレクティブのテキスト入力はサーバー接続後に更新されます。その場合、親ディレクティブのテキスト入力は更新されません。したがって、子ディレクティブ内の ngModel の変更を監視する必要があると思います。どうやってやるの?それは理にかなっていますか?